How to embed other package's struct in golang

末鹿安然 提交于 2019-12-11 06:11:42

问题


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\n", 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:


@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.



来源:https://stackoverflow.com/questions/45897371/how-to-embed-other-packages-struct-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!