Created
May 25, 2023 08:09
-
-
Save nikzayn/4edd4614fb45ea222aaa330da5cc0c07 to your computer and use it in GitHub Desktop.
Example of using omitempty tag using pointers in structs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type BMI struct { | |
Height int | |
Weight int | |
} | |
type Person struct { | |
Name string | |
Age int `json:",omitempty"` | |
BodyMassIndex *BMI `json:",omitempty"` | |
} | |
func main() { | |
p := Person{ | |
Name: "Nikhil", | |
} | |
b, _ := json.Marshal(p) | |
fmt.Println(string(b)) | |
} | |
//Ouput | |
- {"Name":"Nikhil"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment