gpt4 book ai didi

go - 将指向结构的指针添加到 slice

转载 作者:IT王子 更新时间:2023-10-29 01:50:31 25 4
gpt4 key购买 nike

我正在尝试将指向结构的指针添加到 slice 中,但我无法摆脱这个错误:

cannot use NewDog() (type *Dog) as type *Animal in append:
*Animal is pointer to interface, not interface

我怎样才能避免这个错误? (同时仍然使用指针)

package main

import "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()
}

最佳答案

package main

import "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()
}

您不需要指向 Animal 接口(interface)的指针 slice 。

http://golang.org/doc/effective_go.html#pointers_vs_values

关于go - 将指向结构的指针添加到 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17229550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com