登录
首页 >  Golang >  Go问答

函数在接口接收的指针时引发错误?

来源:stackoverflow

时间:2024-03-08 18:54:24 292浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《函数在接口接收的指针时引发错误?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

这就是我遇到的情况,我不明白为什么会出现错误:

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(类型 *i 是指向接口的指针,而不是接口)

*i 更改为 i 可以解决该错误。

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

另外,当函数被定义为接受 i 但它实际上接收到一个指针&foo{})时,为什么它会编译?该函数是否应该期望类似 foo{} 的东西(即不是指针)?


解决方案


对此问题的快速解决方法是使 print_item1 只接受 i 而不是指向 i 的指针。

func print_item1(item I)

原因是 *foo 满足 i 接口,但请记住 *foo 不是 *i

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

好了,本文到此结束,带大家了解了《函数在接口接收的指针时引发错误?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>