Can embedded methods access “parent” fields?

后端 未结 2 1183
时光取名叫无心
时光取名叫无心 2020-12-10 17:58

Background

I\'ve done a fair amount of spec reading and code testing and I think the answer is no, but I want to make sure I\'m not missing anything

相关标签:
2条回答
  • 2020-12-10 18:29

    Go doesn't provide any support for what you're after: the receiver of your Test method is a Bar pointer, and there is no way to tell whether it is embedded or not.

    If you really want to go this route, one option would be to add an interface{} member to Bar and require that types that it be set to the containing type. Initialising this member could either be the responsibility of whoever created the value, or perhaps require callers to pass the value to some ORM method to set it. This isn't particularly pretty, but it's probably the best you can do.

    With that out of the way, is it really that bad to structure the API as db.Save(user) rather than user.Save()? The former offers an obvious way to extend to multiple databases, while the latter seems more likely to rely on global state.

    0 讨论(0)
  • 2020-12-10 18:31

    (If I understood your question correctly,) no, embedding isn't inheritance. It sounds like what you're actually after is an interface

    type Saver interface {
        Save() error
    }
    

    then the relevant parties can implement that.

    You can have a common struct base or whatever that implements common methods and then each higher-level struct can embed base to allow them to share implementation.

    0 讨论(0)
提交回复
热议问题