I cannot figure out how to initialize a nested struct. Find an example here: http://play.golang.org/p/NL6VXdHrjh
package main
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
Proxy: {
Address: "addr",
Port: "80",
}
}
}
Nesting of structure within itself is not allowed. A nested structure can be passed into the function in two ways: Pass the nested structure variable at once. Pass the nested structure members as an argument into the function.
To access the members of the inner structure, we write a variable name of the outer structure, followed by a dot( . ) operator, followed by the variable of the inner structure, followed by a dot( . ) operator, which is then followed by the name of the member we want to access.
You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
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",
},
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With