This question already has an answer here:
I have this struct right now
type ServiceStruct struct {
Name string `json:"name"`
DataStruct struct {
ID string `json:"id"`
Size string `json:"size"`
}
}
But im not sure how to assign values to the elements inside this struct. Specially the DataStruct inside the ServiceStruct
</div>
You can either use an anonymous struct literal (which requires copy-pasting the type of DataStruct
) or assign values to individual fields using =
.
package main
import (
"fmt"
)
type ServiceStruct struct {
Name string `json:"name"`
DataStruct struct {
ID string `json:"id"`
Size string `json:"size"`
}
}
func main() {
s1 := ServiceStruct{
Name: "foo",
DataStruct: struct {
ID string `json:"id"`
Size string `json:"size"`
}{
ID: "bar",
Size: "100",
},
}
s2 := ServiceStruct{
Name: "foo",
}
s2.DataStruct.ID = "bar"
s2.DataStruct.Size = "100"
fmt.Println(s1)
fmt.Println(s2)
// Output:
// {foo {bar 100}}
// {foo {bar 100}}
}
Alternatively, consider giving the type of DataStruct
a name so you can refer to it in the struct literal instead of copy-pasting (which is not recommended).
https://play.golang.org/p/GObadB9WyN
Example of passing/unmarshaling a JSON into your struct. This has been my primary use-case, I hope it is helpful.
package main
import (
"fmt"
"encoding/json"
)
type ServiceStruct struct {
Name string `json:"name"`
DataStruct struct {
ID string `json:"id"`
Size string `json:"size"`
}
}
func main() {
x := `{
"Name": "Fido",
"DataStruct": {
"ID": "Dog",
"Size": "Small"
}
}`
ex := ServiceStruct{}
json.Unmarshal([]byte(x), &ex)
fmt.Println(ex.Name)
}