简体   繁体   中英

Copy map values to struct of pointers

type Foo struct {
    A *string
    B *string
    C *string
    D *string
}

m := map[string]string{"a": "a_value", "b": "b_value", "c": "c_value", "d": "d_value"}

a, b, c, d := m["a"], m["b"], m["c"], m["d"]

foo := Foo{
    A: &a,
    B: &b,
    C: &c,
    D: &d,
}

Playground link

Is there a way to directly copy the map values into the struct, without using the intermediate local variables a , b , c , d ?

Obviously I can't just write

foo := Foo{
    A: &m["a"],
    B: &m["b"],
    C: &m["c"],
    D: &m["d"],
}

because then Go thinks I want to take the address of the (not addressable) value while it is still in the map.

To make it easy, compact and reusable, use a helper function or a closure :

p := func(key string) *string {
    s := m[key]
    return &s
}

foo := Foo{
    A: p("a"),
    B: p("b"),
    C: p("c"),
    D: p("d"),
}

Try it on the Go Playground .

For background and more options, see related: How do I do a literal *int64 in Go?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM