인터페이스 방법 값 수신자와 바늘 수신자의 실현 차이
6769 단어 Golang 학습 노트
package main
import (
"fmt"
)
type AnimalInterface interface {
bake(string) error
}
//Dog ...
type Dog struct {
name string
}
func (dog Dog) bake(w string) error {
fmt.Printf("%s bake %s
", dog.name, w)
return nil
}
type Cat struct {
name string
}
func (cat *Cat) bake(w string) error {
fmt.Printf("%s bake %s
", cat.name, w)
return nil
}
func main() {
var dogBig AnimalInterface = Dog{
name: " ",
}
dogBig.bake(" ")
var dogLittle AnimalInterface = &Dog{
name: " ",
}
dogLittle.bake(" ")
// cannot use Cat literal (type Cat) as type AnimalInterface in assignment:Cat does not implement AnimalInterface (bake method has pointer receiver)
var catHua AnimalInterface = Cat{
name: " ",
}
catHua.bake(" ")
var catBlue AnimalInterface = &Cat{
name: " ",
}
catBlue.bake(" ")
}
var catHua AnimalInterface = Cat{
name: " ",
}
,cannot use Cat literal (type Cat) as type AnimalInterface in assignment:
Cat does not implement AnimalInterface (bake method has pointer receiver)
클래스 방법은 바늘 수신자가 인터페이스를 실현할 때 이 클래스를 가리키는 바늘만이 이 인터페이스를 실현한 것으로 여겨진다. cat는 인터페이스를 실현하지 않은 베이크 방법을 실현했다. *Cat은 인터페이스의 베이크 방법을 실현했기 때문에 컴파일이 통과되지 않았다. 그러나 Dog는 왜 가능할까. Dog는 인터페이스 베이크 방법을 실현했다. *Dog
인터페이스의 베이크 방법다음은 <>을 참조하여 정리한 두 가지 규칙입니다. 먼저 수신자가 값인지 포인터인지 방법을 살펴보겠습니다.
Methods Receivers
Values
(t T)
T and *T
(t *T)
*T
위의 표는 값 수신자라면 실체 유형의 값과 바늘이 대응하는 인터페이스를 실현할 수 있다고 해석할 수 있다.바늘 수신자라면 유형의 바늘만 대응하는 인터페이스를 실현할 수 있다.
그 다음으로 우리는 실체 유형이 값인지 바늘인지의 각도로 본다.
Values
Methods Receivers
T
(t T)
*T
(t T) and (t *T)
위의 표는 다음과 같이 해석할 수 있다. 유형의 값은 값 수신자의 인터페이스만 실현할 수 있다.유형을 가리키는 바늘은 값 수신자의 인터페이스를 실현할 수도 있고 바늘 수신자의 인터페이스를 실현할 수도 있다.
참고
https://qcrao91.gitbook.io/go/interface/zhi-jie-shou-zhe-he-zhi-zhen-jie-shou-zhe-de-qu-bie https://www.flysnow.org/2017/04/03/go-in-action-go-interface.html