如何在Go语言中嵌入其他包的结构体?

huangapple go评论70阅读模式
英文:

How to embed other package's struct in golang

问题

我知道如何在同一个包中嵌入其他结构体,但如何嵌入其他包的结构体呢?

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()
}

当我运行main.go时,它告诉我一个错误:

./main.go:14: b.callMyName未定义(类型*BDog没有字段或方法callMyName)
英文:

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

得分: 1

@simon_xia 是正确的,看起来你可能对Go语言还有点陌生。

首先,欢迎加入这个社区!!

现在稍微扩展一下他的评论...与其为成员/方法提供公共/私有范围,Go语言采用了导出的概念。所以,如果你想允许其他包中的方法访问该方法,只需将方法的签名首字母大写即可 如何在Go语言中嵌入其他包的结构体?

大多数基本的面向对象编程特性在Go语言中以某种方式得到满足,但重要的是要理解Go语言不是一种面向对象的语言

强烈建议你完成整个Go之旅,因为它涵盖了导出的概念以及Go语言的许多其他关键特性。整个旅程可以在一个下午内完成,几年前我通过它大大提高了对该语言的掌握程度。

如果你在完成之后还想深入学习,我发现Go By Example是一个很好的参考点,可以对一些主要主题进行更深入的学习。

英文:

@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 如何在Go语言中嵌入其他包的结构体?

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.

huangapple
  • 本文由 发表于 2017年8月27日 00:14:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/45897371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定