Golang, 함수 인터페이스 인자에 구조체 넣기

00_8_3·2023년 3월 3일
0

Go

목록 보기
5/10

문법이름 모르겠다.

문법 : https://gobyexample.com/interfaces

package main

type Go interface {
	testG() (string)
	testO() (string)
}

type Duck struct {

}

func (d *Duck) testG() string{
	return "asdf"
}

func (d *Duck) testO() string{
	return "asdf"
}

func Test(a Go){

}

func main() {
	aa := &Duck{}
	Test(aa)
}

1 Test 함수에는 Go라는 인터페이스 타입의 인자가 선언이 되어있다.
2 Duck 타입의 파라미터가 들어가진다.
3 Duck 구조체 타입이 Go 인터페이스 메소드를 모두 구현했다.
4 구현된 메소드 testG 또는 testO 둘 중 하나를 주석처리하면 오류가 발생한다.

즉, Go 인터페이스 메소드를 모두 구현한 구조체만이
Test 함수 파라미터로 들어갈 수 있다.

참고

https://github.com/techschool/simplebank/blob/4e5b7f9f2b27da3267d5db12a379e124a581779f/db/sqlc/store.go#L23

https://github.com/techschool/simplebank/blob/4e5b7f9f2b27da3267d5db12a379e124a581779f/db/sqlc/db.go#L19

0개의 댓글