• Home
  • About
    • Jiwon Jeong photo

      Jiwon Jeong

      끊임없이 배우며 성장하는 엔지니어

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

Go 인터페이스 활용

19 Dec 2021

Reading time ~1 minute

Go 구조체와 인터페이스 활용

  • account.go 파일이 다음과 같다.
// account.go DTO

package main

type AccountInterface interface {
	GetToken() string
}

type JointAccount struct {
	Account
}

type Account struct {
	DOCTYPEID string `json:"@account"` // address
	Token     string `json:"token"`
	Num       int
}

func (a *Account) GetToken() string {
	return a.Token
}

  • main.go 내 res 함수를 호출 할 때는 파라미터를 포인터로 전달하지만, 실제로 res 함수 내에서는 인터페이스 파라미터를 포인터로 전달하지 않는다.
package main

import "fmt"

func res(account AccountInterface) string {
	if a, ok := account.(*Account); ok {
		a.Token = "2ndToken"
		return a.Token
	}
	return "error"
}

func main() {
	account := Account{
		DOCTYPEID: "doctest",
		Token:     "1stToken",
	}
	ans := res(&account)
	fmt.Print(ans) // 2ndToken
}



개발일기 Share Tweet +1