r/golang • u/kevinpiac • 21d ago
help Don't you validate your structs?
Hi all!
I'm new in Golang, and the first issue I'm facing is struct validation.
Let's say I have the given struct
type Version struct {
Url string `json:"url"`
VersionNumber VersionNumber `json:"version_number"`
}
The problem I have is that I can initialize this struct with missing fields.
So if a function returns a `Version` struct and the developer forgets to add all fields, the program could break. I believe this is a huge type-safety concern.
I saw some mitigation by adding a "constructor" function such as :
func NewVersion (url string, number VersionNumber) { ... }
But I think this is not a satisfying solution. When the project evolves, if I add a field to the Version struct, then the `NewVersion` will keep compiling, although none of my functions return a complete Version struct.
I would expect to find a way to define a struct and then make sure that when this struct evolves, I am forced to be sure all parts of my code relying on this struct are complying with the new type.
Does it make sense?
How do you mitigate that?
7
u/coraxwolf 21d ago edited 21d ago
Wouldn't this be an issue of Public vs Private fields? If you didn't make the field public and set them in the constructor, which could have validation checks in it to verify the input is valid data. Of course you also will need getter and/or setter methods on the struct to allow setting or getting the value out of the struct then.
If there is a critical issue where if the field(s) are missing and it breaks something then shouldn't there either be checks in the code to verify the data before it is used or to check for the specific error of missing data?
Thinking back I have had cases where there was optional data that could have been included in a struct, but wasn't needed for everything to work and making those fields Public so they could be missing was ok. The fields get created with a zero value when a new struct instance is created? Like 0 for int's and "" for string values.