简体   繁体   English

将 map 值复制到指针结构

[英]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 ?有没有办法直接将 map 值复制到结构中,而不使用中间局部变量abcd

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.因为那时 Go 认为我想获取(不可寻址)值的地址,而它仍在 map 中。

To make it easy, compact and reusable, use a helper function or a closure :为了使其简单、紧凑和可重复使用,请使用辅助工具 function 或闭包

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 .Go 游乐场上试一试。

For background and more options, see related: How do I do a literal *int64 in Go?有关背景和更多选项,请参阅相关: 如何在 Go 中执行文字 *int64?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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