1
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.

icza
  • 389,944
  • 63
  • 907
  • 827
AndreKR
  • 32,613
  • 18
  • 106
  • 168

1 Answers1

0

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    Clever. And kind of obvious really. I still haven't overcome years of training by a language that doesn't inline functions. :( – AndreKR Jun 14 '20 at 20:28