【问题标题】:Copy map values to struct of pointers将映射值复制到指针结构
【发布时间】:2020-06-14 19:58:53
【问题描述】:
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

有没有办法不使用中间局部变量abcd,直接将映射值复制到结构中?

显然我不能只写

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

因为 Go 认为我想在(不可寻址的)值仍在地图中时获取它的地址。

【问题讨论】:

    标签: dictionary pointers go struct


    【解决方案1】:

    为了使其简单、紧凑和可重用,请使用辅助函数或 闭包

    p := func(key string) *string {
        s := m[key]
        return &s
    }
    
    foo := Foo{
        A: p("a"),
        B: p("b"),
        C: p("c"),
        D: p("d"),
    }
    

    Go Playground 上试用。

    有关背景和更多选项,请参阅相关:How do I do a literal *int64 in Go?

    【讨论】:

    • 聪明。真的很明显。我仍然没有通过不内联函数的语言克服多年的培训。 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    相关资源
    最近更新 更多