douxi9245 2015-06-03 14:11
浏览 13

嵌入式结构方法可以了解父/子吗?

I have been working with Go on and off on my free time for a few months and I feel I've been getting a hang of it. Coming from traditional OOP languages, such as Java and PHP, I had a hard time grasping composition and embedding in Go. I think it finally clicked recently and want to use it more, but I have hit a roadblock for one idea I have.

Lets say I have a struct from a package that has a Validate method and I embedded that in my struct in the package I am currently working in. Is there a way (I own both packages) that I can get a reference to the struct that is doing the embedding inside of the Validate method? Kind of like a way to see who called me since I would be calling it on the "parent" instead of the embedded.

I'll try to visualize this...

type B struct {}
func (b B) Validate() {
  // get reference somehow of A obj
}


type A struct {
  B
}

a := A{B{}}
a.Validate()

I feel as though this isn't possible, but it would be cool if you could. I'd imagine that you would need to make A and B both the same interface type for this to work. Any thoughts or help will be much appreciated.

  • 写回答

2条回答 默认 最新

  • douzhizao0270 2015-06-03 14:17
    关注

    Any kind of parent reference is impossible. What would you hope to do with the parent? Since they would be potentially widely different types, they would be incompatible to do anything meaningful with.

    If you need something in common between different types you want an interface, and you will need to pass it in:

    type B struct {}
    func (b B) Validate(parent MyInterface) {
    }
    
    
    type A struct {
      B
    }
    // A implements MyInterface
    a := A{B{}}
    a.Validate(a)
    

    If you can explain what you are actually trying to accomplish there is almost certainly a better way than this.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效