Saturday, May 24, 2025
HomeGolangI want my nulls - Code Evaluation

I want my nulls – Code Evaluation


Howdy,
I’m on the lookout for a approach to retain null values despatched from a REST API server in JSON. Presently, I’m utilizing a struct and unmarshal however this turns Nulls into zeros.

Does anybody have a fast code instance or hyperlink to a great video on this? I attempted with pointers however I’m not understanding the way it helps, I nonetheless see zeros.

sort foo struct {
  Foo *int `json:"foo"`
}



4 Likes

Hello Sivan,

Identical to NobbZ mentioned, you should use a pointer that signifies that the info may not be current

sort Foo struct {
  Bar *string `json:"bar"`
}

Simply do not forget that if you’re utilizing a worth and it is perhaps null it’s worthwhile to make a null examine earlier than utilizing the worth as a existent worth, in any other case you’ll get a panic: runtime error: invalid reminiscence handle or nil pointer dereference, you should use one thing like that:

var foo Foo

//...unmarshall to Foo

if foo.Bar != nil {
// utilizing len() right here is secure
fmt.Println(len(*foo.Bar))
}

You may also wish to examine omitempty and omitzero JSON tags, for cleansing up your JSON outputs, so search a bit about them (omitzero was launched in go 1.24 so it’s fairly new, you may not discover numerous assets about it)



1 Like

One good factor about go is len() being a static operate. You don’t want a null examine on slices earlier than studying size and even earlier than looping over it. A nil-slice will behave like a slice of size 0 for many functions.

However you’re in fact proper for all different primitives, structs and maps.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments