Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a nested struct?

Tags:

go

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",
        }
    }

}
like image 203
sontags Avatar asked Oct 10 '22 09:10

sontags


People also ask

How do you use a struct inside another struct?

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.

How do you access members of a nested structure?

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.

Can you initialize in struct?

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.


2 Answers

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",
    },
}
like image 242
OneOfOne Avatar answered Oct 11 '22 22:10

OneOfOne


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

like image 152
sepehr Avatar answered Oct 11 '22 21:10

sepehr