이 코드는 제대로 실행되지 않습니다이동 상속과 다형성
package main
import "fmt"
type Human interface {
myStereotype() string
}
type Man struct {
}
func (m Man) myStereotype() string {
return "I'm going fishing."
}
type Woman struct {
}
func (m Woman) myStereotype() string {
return "I'm going shopping."
}
func main() {
var m *Man
m = new (Man)
w := new (Woman)
var hArr []*Human
hArr = append(hArr, m)
hArr = append(hArr, w)
for n, _ := range (hArr) {
fmt.Println("I'm a human, and my stereotype is: ",
hArr[n].myStereotype())
}
}
이 존재 :
tmp/sandbox637505301/main.go:29:18: cannot use m (type *Man) as type *Human in append:
*Human is pointer to interface, not interface
tmp/sandbox637505301/main.go:30:18: cannot use w (type *Woman) as type *Human in append:
*Human is pointer to interface, not interface
tmp/sandbox637505301/main.go:36:67: hArr[n].myStereotype undefined (type *Human is pointer to interface, not interface)
하지만이 일이 제대로 실행 (var에 해리는 [] * 인간은 var에 해리의 [에 다시 작성 ] 인간)
package main
import "fmt"
type Human interface {
myStereotype() string
}
type Man struct {
}
func (m Man) myStereotype() string {
return "I'm going fishing."
}
type Woman struct {
}
func (m Woman) myStereotype() string {
return "I'm going shopping."
}
func main() {
var m *Man
m = new (Man)
w := new (Woman)
var hArr []Human // <== !!!!!! CHANGED HERE !!!!!!
hArr = append(hArr, m)
hArr = append(hArr, w)
for n, _ := range (hArr) {
fmt.Println("I'm a human, and my stereotype is: ",
hArr[n].myStereotype())
}
}
출력 OK이다
I'm a human, and my stereotype is: I'm going fishing.
I'm a human, and my stereotype is: I'm going shopping.
나는 이유를 모르겠다. m과 w는 포인터이므로 hArr을 Human에 대한 포인터 배열로 정의하면 코드가 실패하는 이유는 무엇입니까?
는 인터페이스에 포인터을 사용하는 것을 기본 문제가 귀하의 설명
이동에는 상속이 없으므로 "is a"유형 다형성이 없습니다. – JimB
[인터페이스를 사용하여 임의 유형의 대기열 만들기] (https://stackoverflow.com/questions/35595810/using-interfaces-to-create-a-queue-for-arbitrary-types)의 가능한 복제본 – IanAuld