3 ms·
It's a pretty big annoyance with Go though. I hate that all struct fields are optional.
by whateveracct 7y ago
It's a pretty big annoyance with Go though. I hate that all struct fields are optional.
- mdanger007 7y agothere are times when a nil struct field is useful, like for trees and json. very easy to require struct fields by using a constructor
- Nullabillity 7y agoAbsolutely, and Option<T>s are great for modelling that. It just shouldn't be the default.
- whateveracct 7y agoIf it's useful, then the person creating the struct can explicitly set it to nil.
- arendtio 7y agoFWIW, I never had that problem, but I also tend to use constructors for my structs.
- whateveracct 7y agoWhen you use constructors you lose named arguments though. One use-case where this is really painful: I like to encode sum types in Go using an interface with a private dummy method + structs that implement that. I then have a function "match" that takes one function per struct. It's nice to be able to pass these functions as a record since it gets ugly, but due to Go allowing omitted functions to be nil, if I add a case to the sum, I open myself up to NPEs everywhere. If Go had a warning for missing struct fields, it would tell me all the places I'd need to handle a new case.
- AlexCoventry 7y agoIsn't this something you could catch with a linter, if you wanted to?
- whateveracct 7y agoDefinitely but I'm not sure if there's a linter for this. If so, I'd love to use it.
- fauigerzigerk 7y agoI think there is a wider issue. Go simply does not provide a way to restrict the state of public struct fields. Enforcing the initialization of all fields achieves relatively little given that public fields could easily be modified elsewhere. Requiring initialization to anything more specific than an automatic zero value is only useful in languages that have read-only fields. So the only way to handle this in Go is to make struct fields private or accept that all combinations of public field values are valid (including the zero value) and deal with it at the point of use (or rather at all points of use).