如何在golang中嵌入其他包的结构
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 undefined (type *BDog has no field or method callMyName)
@simon_xia 是对的,看起来你可能 对 Go 有点陌生。
首先,欢迎来到社区!!
现在扩展一下他的评论...Go 没有为 member/method 提供 public/private 范围,而是具有 Exporting 的概念。所以如果你想允许从另一个包访问一个方法,只需将方法的签名大写:)
Go 以某种方式满足了 OOP 的大多数 基本 功能,但重要的是要了解 Go is not an object-oriented language.
我强烈推荐通读整个Tour of Go,因为它触及导出的概念以及 Go 的许多其他关键特性语。整个游览可以在一个下午完成,它很多让我在几年前快速掌握这门语言。
如果在那之后您仍然渴望了解更多,我发现 Go By Example 是对一些主要主题进行更深入研究的绝佳参考点。
我知道如何在同一包内的结构中嵌入其他结构,但如何嵌入其他包的结构?
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 是对的,看起来你可能 对 Go 有点陌生。
首先,欢迎来到社区!!
现在扩展一下他的评论...Go 没有为 member/method 提供 public/private 范围,而是具有 Exporting 的概念。所以如果你想允许从另一个包访问一个方法,只需将方法的签名大写:)
Go 以某种方式满足了 OOP 的大多数 基本 功能,但重要的是要了解 Go is not an object-oriented language.
我强烈推荐通读整个Tour of Go,因为它触及导出的概念以及 Go 的许多其他关键特性语。整个游览可以在一个下午完成,它很多让我在几年前快速掌握这门语言。
如果在那之后您仍然渴望了解更多,我发现 Go By Example 是对一些主要主题进行更深入研究的绝佳参考点。