I do not embed structs anymore. It is almost always a mistake. I would confidently place it in the "you should be required to import 'unsafe' to use this feature" bin.
I do not embed structs anymore. It is almost always a mistake. I would confidently place it in the "you should be required to import 'unsafe' to use this feature" bin.
Introduction of proper discriminated unions would be great.
type Order struct {
Type OrderType
CommonAttr1 int
CommonAttr2 string
}
type OrderTypeA struct {
Order
TypeAAttr1 int
TypeAAttr2 string
}
type OrderTypeB struct {
Order
TypeBAttr1 int
TypeBAttr2 string
}
And yes you should convert to OrderTypeA or OrderTypeB at the first opportunity in domain code, and only convert from them at the latest opportunity.You seem to be under the impression that I'm advocating for something like
type OrderUnion struct {
CommonAttr1 int
CommonAttr2 string
TypeAAttrs
TypeBAttrs
}
That's what I consider going crazy.Go can only downcast through interfaces so there's something missing to your approach to unions, isn't there?
How would you convert Order to OrderTypeA? You would need some other source to fill TypeAAttr1 and TypeAAttr2 with.
Assuming they've got discriminators and some sense of type union, sure.
> I just showed a data model with a discriminator (.Type)
Which won't let you recover the additional fields from a pointer because you can't downcast, so that's insufficient for a union. AFAIK you need to combine this with interfaces, which I already know how to do.
> These are largely irrelevant in a discussion about type embedding.
Don't tell me, you brought it up.
But yes, for anything more complicated I have generally regretted trying to embed structs. I think requiring "unsafe" is a bit too strong, but I think the syntax should've been uglier / more in-your-face to discourage its use.
(Fellow 10+ years Go user.)
As long as these two aren't there, embedding structs is literally identical to dispatching methods, and can't be used for anything else due to lack of state management through it. You have to manage the states externally anyways from a memory ownership perspective.