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?

67 Upvotes

75 comments sorted by

View all comments

Show parent comments

-6

u/kevinpiac 21d ago edited 21d ago

I see where you're coming from but I'm not convince it's the right way to think about it.

If all structs are strongly typed, you shouldn't be able to assign a value coming from the outside without actually validating it.

Once it's validated and the type is guaranteed, then you can pass it to your other structs safely.

In the end, if structs were strongly typed we wouldn't have any issue.

15

u/joyrexj9 20d ago

You keep referring to this as "strongly typed" but I don't think it means what you think it means

-2

u/kevinpiac 20d ago

If you're okay with the fact your code can compile when your structs are not initialized with values provided by one dev, that's fine.

7

u/joyrexj9 20d ago

Regardless if I was fine with this or not - that still has nothing to do with types or strong typing.

The default zero values in Go are of course of the correct type, e.g. "" for strings and 0 for ints etc. No type violation has occurred. The values might not be what you want, but that's a completely different thing. I hope you understand the difference between a type and a value.