Well, any specific reason to not make Proxy its own struct?
Anyway you have 2 options:
The proper way, simply move proxy to its own struct, for example:
type Configuration struct {
Val string
Proxy Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy{
Address: "addr",
Port: "port",
},
}
fmt.Println(c)
fmt.Println(c.Proxy.Address)
}
The less proper and ugly way but still works:
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}
Answer from OneOfOne on Stack OverflowWell, any specific reason to not make Proxy its own struct?
Anyway you have 2 options:
The proper way, simply move proxy to its own struct, for example:
type Configuration struct {
Val string
Proxy Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy{
Address: "addr",
Port: "port",
},
}
fmt.Println(c)
fmt.Println(c.Proxy.Address)
}
The less proper and ugly way but still works:
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}
If you don't want to go with separate struct definition for nested struct and you don't like second method suggested by @OneOfOne you can use this third method:
package main
import "fmt"
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
}
c.Proxy.Address = `127.0.0.1`
c.Proxy.Port = `8080`
}
You can check it here: https://play.golang.org/p/WoSYCxzCF2
Nested Struct
How to created nested struct
When my struct has another anonymous struct as its field, how do I initialize it?
How to print nicely a nested struct
Hey! So are you looking to do anything more than just view the data that's in those structs? For like debugging purposes. A few ways that come to mind to pretty print structs are:
-
Printf
fmt. Printf("%#v\n", theStruct) -
Marshal with indent and then print the bytes
https://golang.org/pkg/encoding/json/#MarshalIndent
3. Use a third party library like go spew https://github.com/davecgh/go-spew
If you want to do more with it than just pretty print, then implementing the stringer interface seems like a good way to go. You'll need to do it for each type as you said.
Sorry if I misunderstood your question!
More on reddit.comVideos
How do you access data from within a nested struct?
I used https://mholt.github.io/json-to-go/ to turn an JSON API response from https://api.battlemetrics.com/servers?filter[game]=rust into a struct.
Data.Attributes.Name doesn't seem to work to get the data from the struct in this case: https://go.dev/play/p/904eFMv6oKU
The code is based on https://www.youtube.com/watch?v=aYk8XAKxhxU
Example:
type Human struct {
Name string
Age uint8
Dog struct {
Breed string
Age uint8
}
}How do I initialize a variable of type Human that also has a Dog in its initialization?
I'm running into syntax errors when I just write braces and field names.
Hello everyone! I'm trying to learn go, and to do so I've created a little quiz game to study psychopathology for an exam. My problem is that I don't like the code I've wrote, so I'm trying to do better, hoping to learn good go practices along the way.
My question is: if I have a nested struct, with maps and stuff like this...:
type Disorders struct {
Disorders []Disorder
}
type Disorder struct {
Name string
Symptoms Symptom
// More stuff
}
type Symptom struct {
Cognitive map[string]string
Emotional map[string]string
// More stuff
}
...what is the cleanest way to write a .String() method for everyone of them, that lets me specify the kind of symptom, the key of the map, etc.
I load the values from a JSON, so it looks like I can't use the stringer tool
Do you see a better solution to writing every .String() method manually?
Btw I wanted to thank this community, you're all very inclusive and supportive, and it's one of the subs I read from most gladly!
Hey! So are you looking to do anything more than just view the data that's in those structs? For like debugging purposes. A few ways that come to mind to pretty print structs are:
-
Printf
fmt. Printf("%#v\n", theStruct) -
Marshal with indent and then print the bytes
https://golang.org/pkg/encoding/json/#MarshalIndent
3. Use a third party library like go spew https://github.com/davecgh/go-spew
If you want to do more with it than just pretty print, then implementing the stringer interface seems like a good way to go. You'll need to do it for each type as you said.
Sorry if I misunderstood your question!
I personally use this snippet func PrintJSON(obj interface{}) { bytes, _ := json.MarshalIndent(obj, "\t", "\t") fmt.Println(string(bytes)) }
Hi gophers, I'm new to golang so apologies in advance if this is a dumb question, but how do you iterate through nested structs and print the fields and values of each?
So far I've got something like :
`fields := reflect.TypeOf(p)
values := reflect.ValueOf(p)
num := fields.NumField()
for i := 0; i < num; i++ {
field := fields.Field(i)
value := values.Field(i)
fmt.Print(field.Name, "is", value, "\n")
}`
Which is effective for a single struct but ineffective for a struct that contains another struct. Here's the example code I'm trying to experiment with to learn interfaces, structs and stuff: https://go.dev/play/p/kfBc31b-VoI
Sorry for my poor English, but I would appreciate any advice, pointers or criticism. thanks!
To put it simply, you goofed the syntax of a slice literal slightly. Your mistake is fairly logical, but sadly it doesn't work.
The following is a fixed version:
Copyv := &important{ client: "xyz", Response: []Summary{
{
Name: "test",
Metadata: Clientdata { "404040"},
},
},
}
A slice literal is defined like so:
Copy[]type{ items... }
It wasn't clear how you wanted to approach it, as your Response struct implies []VmSummary info, but you are feeding it []Summary.
Also, check https://blog.golang.org/go-slices-usage-and-internals on initialization of arrays.
Something like that?
Copytype important struct {
client string `json:"client"`
Response []Summary `json:"response"`
}
type Summary struct {
Name string `json:"name"`
Metadata Clientdata `json:"metadata"`
}
type Clientdata struct {
Income string `json:"income"`
}
func main() {
v := &important{
client: "xyz",
Response: []Summary{
{
Name: "test",
Metadata: Clientdata{"404040"},
},
},
}
}