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 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染