<分区>
所以这就是我遇到的,我不明白为什么会出错:
package main
import (
"fmt"
)
// define a basic interface
type I interface {
get_name() string
}
// define a struct that implements the "I" interface
type Foo struct {
Name string
}
func (f *Foo) get_name() string {
return f.Name
}
// define two print functions:
// the first function accepts *I. this throws the error
// changing from *I to I solves the problem
func print_item1(item *I) {
fmt.Printf("%s\n", item.get_name())
}
// the second function accepts *Foo. works well
func print_item2(item *Foo) {
fmt.Printf("%s\n", item.get_name())
}
func main() {
print_item1(&Foo{"X"})
print_item2(&Foo{"Y"})
}
两个相同的函数接受一个参数:指向接口(interface)或实现它的结构的指针。
第一个接受接口(interface)指针的不编译错误 item.get_name undefined (type *I is pointer to interface, not interface)
.
从 *I
更改为 I
可解决错误。
我想知道的是为什么不同?第一个函数非常常见,因为它允许单个函数与各种结构一起使用,只要它们实现了 I
接口(interface)。
此外,当函数被定义为接受 I
但它实际上接收到一个指针 (&Foo{}
) 时,该函数为何会编译? ?该函数是否应该期待类似 Foo{}
的内容(即不是指针)?