snippetgoCritical
How to initialize a nested struct?
Viewed 0 times
nestedinitializehowstruct
Problem
I cannot figure out how to initialize a nested struct. Find an example here:
http://play.golang.org/p/NL6VXdHrjh
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",
}
}
}Solution
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:
The less proper and ugly way but still works:
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",
},
}Code Snippets
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)
}c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}Context
Stack Overflow Q#24809235, score: 271
Revisions (0)
No revisions yet.