Avatar ·

错误“指向接口的指针,而非接口”:如何在Go中正确传递接口?

大家好!我是Go新手,遇到了一个奇怪的编译错误:“*MyInterface is pointer to interface, not interface”。 我有一个接口和实现它的结构体: ```go type Animal interface { Speak() string } type Dog struct{} func (d *Dog) Speak() string { return "Woof!" } ``` 我想将指向结构体的指针传递给接受接口的函数: ```go func MakeSound(a Animal) { fmt.Println(a.Speak()) } func main() { dog := &Dog{} MakeSound(dog) // 正常工作 } ``` 但如果我尝试传递**指向接口的指针**(不知为何),就会得到错误: ```go func main() { var animalInterface Animal animalInterface = &Dog{} MakeSound(&animalInterface) // 错误:cannot use &animalInterface (variable of type *Animal) as type Animal in argument to MakeSound } ``` 为什么会这样?传递`*Dog`(它实现了接口)和`*Animal`(指向接口的指针)之间有什么区别?什么时候可能需要用到?