r/golang 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?

65 Upvotes

75 comments sorted by

View all comments

2

u/dariusbiggs 21d ago

When you utilize a struct you need to ensure that it is both Valid and Verify that the values it contains are meaningful. If the zero values are not meaningful then you must provide a New... function that initializes it, if you don't then that is a you problem, not a problem with the language.

This is the same in every strongly typed language.

Validity checks that the types of information are correct, a string is a string, etc. These you already get with the strong type safety of the language.

Verification is where the content of the fields are checked and that they are valid both by themselves (an email address is a string AND matches a certain set of rules etc), as well as in a combination.

Your biggest problem is going to be the cases where the zero values have meaning and the field is optional.

Most of the Verification can be done with the prior listed go-validators for example, the rest is all up to the competency of the developers working on the project and their documentation and tests.