duansha3771
2017-08-26 16:14
浏览 193
已采纳

如何在golang中嵌入其他包的结构

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
", 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)

图片转代码服务由CSDN问答提供 功能建议

我知道如何将其他结构嵌入同一个程序包中的结构,但是如何嵌入其他程序包中的结构?

dog.go

 包dog 
 
import“ fmt” 
 
type Dog struct {
 Name string 
} \  n 
func(此* Dog)callMyName(){
 fmt.Printf(“狗我的名字是%q 
”,this.Name)
} 
   
 
  

main.go

 包main 
 
import“ / path / to / dog” 
 
type BDog结构{
 dog.Dog 
名称字符串 
} 
 
func main(){
b:= new(BDog)
 b.Name =“这是狗的名字” 
 b.name =“这是BDog的名字” 
 b.callMyName  ()
} 
   
 
 

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

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtttlua7165 2017-08-26 16:47
    已采纳

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题