登录
首页 >  Golang >  Go问答

如何在 Go 中为接口分配指针

来源:stackoverflow

时间:2024-04-14 17:03:36 136浏览 收藏

大家好,今天本人给大家带来文章《如何在 Go 中为接口分配指针》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

package main

import "fmt"

type intr interface {
    String() string
}

type bar struct{}

func (b *bar) String() string {
    return "bar"
}

type foo struct {
    bar *intr
}

func main() {
    bar1 := bar{}
    foo1 := foo{bar: &bar1} 
    fmt.Println(foo1)
}

我收到编译时错误:

不能在字段值中使用 &bar1(类型 *bar)作为类型 *intr:*intr 是指向接口的指针,而不是接口

为什么会出现这个错误? 如何分配foo.bar


解决方案


您将其分配给接口的指针。将字段类型更改为接口后,它将起作用:

type foo struct {
    bar intr
}

很少需要接口指针。

终于介绍完啦!小伙伴们,这篇关于《如何在 Go 中为接口分配指针》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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