go - 将指针传递给接口(interface)时函数抛出错误?

标签 go

<分区>

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

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

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

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

此外,当函数被定义为接受 I 但它实际上接收到一个指针 (&Foo{}) 时,该函数为何会编译? ?该函数是否应该期待类似 Foo{} 的内容(即不是指针)?

最佳答案

对此的快速修复是让 print_item1 只接受 I 而不是指向 I 的指针。

func print_item1(item I)

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

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

关于go - 将指针传递给接口(interface)时函数抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53762540/

相关文章:

go - 类型转换运算符重载为 'GO' 中的全局函数

戈朗 : Hello world doesn't print to screen and program doesnt exit

parsing - 将 String 转换为完全相同的 Int

go - 如何模拟客户端和服务器之间的完全网络丢失?

go - 将图像从 *image.YCbCr 转换为 *image.RGBA

testing - 如何在 Golang 中测试日志记录(log.Println)?

go - GoBuffalo CSRF生产上的问题

go - for init 语句只进入函数一次

python - Golang 相当于 Python 的 NotImplementedException

struct - 编写单例结构的更短方法