0

Please see the code sample below (playground). I think my question is explained by the code itself. For some reason, I want to use a string variable to determine the struct field name, not explicitly mention the field. I know this is possible, but I don't know how to start :(.

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)
}
Rogier Lommers
  • 2,263
  • 3
  • 24
  • 38
  • You should also evaluate whether a map would be a more suitable container for your data. –  Apr 19 '18 at 18:51
  • Thanks for your comment, however the duplicate thread explains how to retrieve the value of the field having the exact name. I want to set the value by providing a `string`-name. – Rogier Lommers Apr 19 '18 at 18:58

0 Answers0