dqj29136 2018-12-13 13:04
浏览 5

将指针传递给接口时函数抛出错误? [重复]

This question already has an answer here:

So this is what I ran into, and I can't understand why the error:

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
", item.get_name())
}

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

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

Two identical functions accept a single argument: a pointer to either the interface, or the struct that implements it.
The first one that accepts the pointer to the interface does not compile with an error item.get_name undefined (type *I is pointer to interface, not interface).
Changing from *I to I solves the error.

What I'd like to know is WHY the difference? The first function is very common as it allows a single function to be used with various structs as long as they implement the I interface.

Also, how come that the function compiles when it is defined to accept I but it actually receives a pointer (&Foo{})? Should the function expect something like Foo{} (i.e. NOT a pointer)?

</div>
  • 写回答

1条回答 默认 最新

  • dongyidao1461 2018-12-13 13:10
    关注

    The quick fix to this is to make the print_item1 just accept an I rather than an pointer to I.

    func print_item1(item I)
    

    The reason for this is that *Foo satisfies the I interface but remember that *Foo is not an *I.

    I would highly suggest reading Russ Cox's explanation of the implementation of interfaces

    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加