Why struct isn’t getting any data on unmarshal in Go?

Among first few problems, a go lang programmer will probably be struggling with a blank struct. Structs have blank values when one of the following things are wrong:

1. Invalid Naming Conventions:

First letter of fields in struct should be capital. For example


//Invalid name 	
type Person struct {
    name string
    age  int
}

//Valid Name
type Person struct {
    Name string
    Age  int
}

2. Invalid Matches:

Consider this is the json which we can’t change.


{
 FirstName: "John Doe",
 Age: "30",
}

 


//Results in blank data 	
type Person struct {
    FirstName string //This will match first_name but we have FirstName
    Age  int //This will match age but we have Age
}

//The fix
type Person struct {
    FirstName string `json:"FirstName"`
    Age  int `json:"Age"`
}
Why struct isn’t getting any data on unmarshal in Go?

3 thoughts on “Why struct isn’t getting any data on unmarshal in Go?

Leave a Reply to S. Taylor Cancel reply

Your email address will not be published. Required fields are marked *

Scroll to top