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