Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang how to check struct field int is set? [duplicate]

Tags:

go

With golang script, I have a struct type and json below

struct

admin

type Admin struct {
   Id string `json:"id"`
   Status int `json:"status"`
}

json

jsonData

{
    "id": "uuid"
}

When I using json.Unmarshal(jsonData, &admin) with jsonData above does not have status value

Default value of admin.Status is 0. How i can check admin.Status is not set?

Thanks so much!

like image 419
Hung Quyen Avatar asked Dec 02 '25 14:12

Hung Quyen


1 Answers

Use a pointer for Status field:

package main

import (
    "fmt"
    "encoding/json"
)

type Admin struct {
   Id string `json:"id"`
   Status *int `json:"status"`
}

func main() {
    b := []byte(`{"id": 1}`)
    r := new(Admin)
    json.Unmarshal(b, r)
    fmt.Println(r.Status)

    b2 := []byte(`{"id": 1, "status": 2}`)
    r2 := new(Admin)
    json.Unmarshal(b2, r2)
    fmt.Println(*r2.Status)
}

When its not present in Json, the pointer would be nil.

like image 111
Saurav Prakash Avatar answered Dec 06 '25 17:12

Saurav Prakash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!