登录
首页 >  Golang >  Go问答

传递接口指针作为函数参数

来源:stackoverflow

时间:2024-03-14 23:15:29 443浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《传递接口指针作为函数参数》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在尝试理解 golang (1.12) 接口。我发现接口指针必须显式取消引用,与结构不同:

import "fmt"

// a simple interface with one function
type myinter interface {
    hello()
}

// implement myinter
type mystruct struct {}

func (mystruct) hello() {
    fmt.println("i am t!")
}

// some function that calls the hello function as defined by myinter
func callhello(i *myinter) {   
    i.hello()  // <- cannot resolve reference 'hello'
}

func main() {
    newmystruct := &mystruct{}
    callhello(newmystruct)
}

在这里,我的 callhello 函数无法解析对接口中定义的 hello 函数的引用。当然,取消引用接口是可行的:

func callhello(i *myinter) {   
    (*i).hello()  // <- works!
}

但是在结构体中,我们可以直接调用函数,不需要这种繁琐的解引用符号:

func callHello(s *mystruct) {   
    s.hello()  // <- also works!
}

为什么会出现这样的情况呢?我们必须显式取消引用 interface 指针是否有原因? go 是否试图阻止我将 interface 指针传递给函数?


解决方案


这与类型系统的工作方式有关。接口类型 i 定义方法集。该方法集是为类型 i 定义的,而不是为类型 *i 定义的。因此,*i 的使用受到限制。当函数要设置接口值时可以使用它,但很少见:

func f(x *error) {
  *x = fmt.errorf("some error")
}

请注意,接口本身可以有一个底层指针值:

func f(x someInterface) {
   *x.(*someType) = value
}

func main() {
   x := someType{}
   f(&x)
}

这对于非接口类型是不同的。当您为非接口类型 t 定义方法时,将为 t*t 定义该方法。如果为 *t 定义方法,则仅为 *t 定义,而不为 t 定义。

本篇关于《传递接口指针作为函数参数》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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