我正在嘗試將指向結(jié)構(gòu)的指針添加到切片,但無法消除此錯誤: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 回答

呼喚遠(yuǎn)方
TA貢獻(xiàn)1856條經(jīng)驗 獲得超11個贊
只需將您的代碼更改為:
func main() {
pets := make([]Animal, 2)
pets[0] = NewDog()
pets[0].Speak()
}
接口值已經(jīng)是一個隱式指針。
- 2 回答
- 0 關(guān)注
- 200 瀏覽
添加回答
舉報
0/150
提交
取消