duansha3771 2017-08-26 16:14
浏览 238
已采纳

如何在golang中嵌入其他包的结构

I know how to embed other struct in struct within a same package, but how to embed other package's struct?

dog.go

package dog

import "fmt"

type Dog struct {
    Name string
}

func (this *Dog) callMyName() {
    fmt.Printf("Dog my name is %q
", this.Name)
}

main.go

package main

import "/path/to/dog"

type BDog struct {
    dog.Dog
    name string
}

func main() {
    b := new(BDog)
    b.Name = "this is a Dog name"
    b.name = "this is a BDog name"
    b.callMyName()
}

When I run main.go, it tell me a error:

./main.go:14: b.callMyName undefined (type *BDog has no field or method callMyName)
  • 写回答

1条回答 默认 最新

  • dtttlua7165 2017-08-26 16:47
    关注

    @simon_xia is right and it looks like you might be a little new to Go.

    First off, welcome to the community!!

    Now to expand a bit on his comment... instead of providing public/private scope for a member/method, Go has the concept of Exporting. So if you want to allow a method to be accessed from another package, just capitalize the method's signature :)

    Most of the basic features of OOP are satisfied in some way by Go, but it's important to understand that Go is not an object-oriented language.

    I'd highly recommend working your way through the entire Tour of Go since it hits this concept of Exporting as well as many, many other key features of the Go language. The entire tour can be finished in an afternoon and it did a lot to get me up to speed on the language a few years back.

    If you're still hungry for more after that, I found Go By Example to be an awesome point of reference for a bit of a deeper study into some major topics.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记