将指向结构体的指针添加到切片中

huangapple go评论76阅读模式
英文:

Adding a pointer to a struct to a 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()
}
英文:

I'm trying to add a pointer to a struct to a slice, but I can't get rid of this error:

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

How can I avoid this error? (while still using pointers)

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

答案1

得分: 5

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

You don't need a Slice of pointers to Animal interfaces.

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

答案2

得分: 2

只需将您的代码更改为:

func main() {
  pets := make([]Animal, 2)
  pets[0] = NewDog()
  pets[0].Speak()
}

接口值已经是一个隐式指针。

英文:

just change your code to:

func main() {
  pets := make([]Animal, 2)
  pets[0] = NewDog()
  pets[0].Speak()
}

a interface value is already an implicit pointer.

huangapple
  • 本文由 发表于 2013年6月21日 15:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/17229550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定