【发布时间】:2019-05-14 17:02:42
【问题描述】:
所以这就是我遇到的,我不明白为什么会出错:
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"})
}
两个相同的函数接受一个参数:一个指向接口的指针,或者实现它的结构。
接受指向接口的指针的第一个不会编译错误item.get_name undefined (type *I is pointer to interface, not interface)。
从 *I 更改为 I 可解决该错误。
我想知道为什么会有不同?第一个函数非常常见,因为它允许单个函数与各种结构一起使用,只要它们实现I 接口即可。
另外,为什么函数被定义为接受I,但它实际上接收到一个指针 (&Foo{})?该函数是否应该期待 Foo{} 之类的东西(即不是指针)?
【问题讨论】:
-
stackoverflow.com/a/44372954/2664120也许这个答案对你有帮助?
-
没有理由使用指向接口的指针。把它们都去掉就没有问题了。
标签: go