问题描述
我知道如何在同一个包中的struct中嵌入其他struct,但是如何嵌入其他包的struct?
dog.go
包狗
导入fmt
类型狗结构{
名称字符串$
$ b func(this * Dog)callMyName(){
fmt.Printf(Dog my name is%q\\\
,this.Name)
}
.go
package main
import/ path / to / dog
type BDog struct {
dog.Dog
name字符串
}
func main(){
b:= new(BDog)
b.Name =这是一个狗的名字
b。 name =这是一个BDog名称
b.callMyName()
}
当我运行main.go时,它告诉我一个错误:
./ main.go:14:b.callMyName未定义(类型* BDog没有字段或方法callMyName)
@simon_xia是对的,它是厕所ks like you might 对Go有点新颖。
首先,欢迎来到社区!!现在扩展一下他的评论......而不是为成员/方法提供公共/私人范围,Go的概念是。所以如果你想允许一个方法从另一个包中被访问,只需要大写方法的签名:)
大多数基本的特性: OOP在某种程度上被Go满意,但重要的是要明白,。
我强烈建议通过整个,因为它符合Export的这个概念以及Go语言的许多其他重要功能。整个旅程都可以在一个下午完成,而且很多让我在几年前加快语言速度。
如果在此之后你仍然渴望更多,我发现是一个很棒的参考点对一些主要议题进行深入研究。
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)
@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.
这篇关于如何在golang中嵌入其他软件包的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!