我知道如何在同一包中的结构中嵌入其他结构,但是如何嵌入其他包的结构?
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 undefined (type *BDog has no field or method callMyName)
@simon_xia 是对的,看起来像你might对 Go 有点陌生。
首先欢迎来到社区!!
现在扩展一下他的评论...Go 没有为成员/方法提供公共/私有范围,而是具有以下概念:出口 https://tour.golang.org/basics/3。因此,如果您想允许从另一个包访问某个方法,只需将该方法的签名大写即可:)
大部分的basicGo 在某种程度上满足了 OOP 的特性,但理解这一点很重要Go 不是面向对象的语言 https://golang.org/doc/faq#Is_Go_an_object-oriented_language.
I'd 强烈推荐努力完成整个过程围棋之旅 https://tour.golang.org/list因为它触及了导出的概念以及 Go 语言的许多其他关键功能。整个行程一个下午就能结束,确实如此a lot几年前让我快速掌握这门语言。
如果在那之后你仍然渴望更多,我发现举例说明 https://gobyexample.com成为深入研究某些主要主题的绝佳参考点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)