使用string var来填充struct

时间:2018-04-19 18:47:14

标签: go struct reflection

请参阅下面的代码示例(playground)。我认为我的问题是由代码本身解释的。出于某种原因,我想使用字符串变量来确定struct字段名称,而不是明确提到该字段。我知道这是可能的,但我不知道如何开始:(。

package main

import "fmt"

type Usage struct {
    Primary    *Rendition
    Additional *Rendition
}

type Rendition struct {
    ID        int
    SomeField string
}

func main() {
    r1 := Rendition{
        ID:        1,
        SomeField: "somevalue",
    }

    var myName = "Primary"

    u1 := Usage{
        // now instead of explicit mention "primary", I want to use the value of
        // the above myName var (which is "Primary") in order to fill the struct.
        Primary: &r1,
    }

    fmt.Print(u1.Primary)
}

0 个答案:

没有答案