Live data from Hacker News

Be careful with Go struct embedding

mattjhall.co.uk

1–10 of 101 posts

Re: Be careful with Go struct embedding

#6
If you need to grab a particular struct's version of the data, you can via `opts.BarService.URL` or `opts.FooService.URL`: https://go.dev/play/p/MUSYJhmoC2D

Still worth being careful, but it can be useful when you have a set of common fields that everything of a certain group will have (such as a response object with basic status, debug info, etc. and then additional data based on the particular struct). I don't know why they let you embed multiple layers and multiple objects though. I've never gotten value out of anything but a "here's a single set of common fields struct embedding".

Re: Be careful with Go struct embedding

#7
So I got curious and I looked at the compiler source code, and it does a depth-first search.

The fascinating bit to me is that there is a consolidateMultiples function in go/src/go/types/lookup.go (lines 286-304) that detects when multiple embedded types at the same depth provide the same field name. I wonder why they don’t do this for all levels. How deep could this even be in practice for it to matter? You could just have a hashmap with them all.

Re: Be careful with Go struct embedding

#8
post #3
post #2

That’s actually crazy. Why is this even a feature?

Because type Foo struct { sync.Mutex whatever string } var foo Foo foo.Lock() foo.whatever = 42 foo.Unlock() is convenient.

It's dangerous. This is awful.

Any coding construct that can cause defects is an antipattern. Your language should discourage defects by design. Especially if the faults crop up at runtime.

This struct field dereferencing is like NULLs and "goto".

Language design that is anti-defect yet ergonomic include the modern Option and Result as seen in languages such as Swift and Rust, with first class destructuring that doesn't make it painful to use. They're almost impossible to misuse, yet feel convenient instead of frictionful. Rust's sum types and matching are another set of examples. Hopefully these patterns spread to more languages, because they're safe and convenient.

Re: Be careful with Go struct embedding

#10
post #7

So I got curious and I looked at the compiler source code, and it does a depth-first search. The fascinating bit to me is that there is a consolidateMultiples function in go/src/go/types/lookup.go (lines 286-304) that detects when multiple embedded types at the same depth provide the same field name. I wonder why they don’t do this for all levels. How deep could this even be in practice for it to matter? You could ju…

> I wonder why they don’t do this for all levels. How deep could this even be in practice for it to matter? You could just have a hashmap with them all.

While it may seem questionable for fields; it applies to methods too and is potentially more useful as a way to override them when doing struct embedding but wanting to preserve an interface.

Post reply on HN