我正在嘗試將指向結構的指針添加到切片,但無法消除此錯誤:cannot use NewDog() (type *Dog) as type *Animal in append: *Animal is pointer to interface, not interface我怎樣才能避免這個錯誤?(同時仍然使用指針)package mainimport "fmt"type Animal interface { Speak()}type Dog struct {}func (d *Dog) Speak() { fmt.Println("Ruff!")}func NewDog() *Dog { return &Dog{}}func main() { pets := make([]*Animal, 2) pets[0] = NewDog() (*pets[0]).Speak()}
2 回答
呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
只需將您的代碼更改為:
func main() {
pets := make([]Animal, 2)
pets[0] = NewDog()
pets[0].Speak()
}
接口值已經是一個隱式指針。
- 2 回答
- 0 關注
- 211 瀏覽
添加回答
舉報
0/150
提交
取消
