}
以上代码可以运行,但是把mathoed中的struct换成指针为什么就不能运行了,如下所示
package main import ( "fmt" ) type Human struct { name string age int phone string } type Student struct { Human school string loan float32 } type Employee struct { Human company string money float32 } func (h *Human) SayHi() { ("Hi,I am %s you can call me on %s\n",,) } func (h *Human) sing(lyrics string) { ("la la la la la la la la la la la la ...",lyrics) } func (e *Employee) SayHi() { ("Hi, I am %s, I work at %s. Call me on %s\n", , , ) //Yes you can split into 2 lines here. } type Men interface { SayHi() sing(lyrics string) } func main() { mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00} paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100} sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000} Tom := Employee{Human{"Sam", 36, "444-222-XXX"}, "Things Ltd.", 5000} //定义Men类型的变量i var i Men //i能存储Student i = mike ("this is mike, astudent") () ("November rain") //i 也能存储Employee i = Tom ("this is tom, an Employee:") () ("Born to be wild") //定义了slice Men ("Let's use a slice of Men and see what happens") x := make([]Men,3) //这三个都是不同类型的元素,但是他们实现了interface同一个接口 x[0],x[1],x[2] = paul,sam,mike for _,value := range x{ () } }报错是接口不能接受此种类型了 如下:
"C:\Program Files (x86)\JetBrains\Gogland 163.10154.18\bin\" C:/Go\bin\ run C:/Users/Administrator/GoglandProjects/untitled/src/
# command-line-arguments
src\:54: cannot use mike (type Student) as type Men in assignment:
Student does not implement Men (SayHi method has pointer receiver)
src\:60: cannot use Tom (type Employee) as type Men in assignment:
Employee does not implement Men (SayHi method has pointer receiver)
src\:69: cannot use paul (type Student) as type Men in assignment:
Student does not implement Men (SayHi method has pointer receiver)
src\:69: cannot use sam (type Employee) as type Men in assignment:
Employee does not implement Men (SayHi method has pointer receiver)
src\:69: cannot use mike (type Student) as type Men in assignment:
Student does not implement Men (SayHi method has pointer receiver)
Process finished with exit code 2
对此深深不解,以作记录。