【问题标题】:Function throws error when passing a pointer to interface? [duplicate]将指针传递给接口时函数抛出错误? [复制]
【发布时间】:2019-05-14 17:02:42
【问题描述】:

所以这就是我遇到的,我不明白为什么会出错:

package main

import (
    "fmt"
)

// define a basic interface
type I interface {
    get_name() string
}

// define a struct that implements the "I" interface
type Foo struct {
    Name string
}

func (f *Foo) get_name() string {
    return f.Name
}

// define two print functions:
// the first function accepts *I. this throws the error
// changing from *I to I solves the problem
func print_item1(item *I) {
    fmt.Printf("%s\n", item.get_name())
}

// the second function accepts *Foo. works well
func print_item2(item *Foo) {
    fmt.Printf("%s\n", item.get_name())
}

func main() {
    print_item1(&Foo{"X"})
    print_item2(&Foo{"Y"})
}

两个相同的函数接受一个参数:一个指向接口的指针,或者实现它的结构。
接受指向接口的指针的第一个不会编译错误item.get_name undefined (type *I is pointer to interface, not interface)
*I 更改为 I 可解决该错误。

我想知道为什么会有不同?第一个函数非常常见,因为它允许单个函数与各种结构一起使用,只要它们实现I 接口即可。

另外,为什么函数被定义为接受I,但它实际上接收到一个指针 (&Foo{})?该函数是否应该期待 Foo{} 之类的东西(即不是指针)?

【问题讨论】:

标签: go


【解决方案1】:

对此的快速解决方法是让print_item1 只接受I 而不是指向I 的指针。

func print_item1(item I)

原因是*Foo 满足I 接口,但请记住*Foo 不是*I

我强烈建议阅读Russ Cox's explanation of the implementation of interfaces

【讨论】:

  • 原因是对的,我真的不建议在不知道上下文的情况下接受I
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多