Assign to struct field dynamically (type t does not support indexing)

3,907 views
Skip to first unread message

Jay Adams

unread,
May 21, 2021, 5:38:15 PM5/21/21
to golang-nuts
Greetings,

I need to be able to assign a value to a struct field where I specify the field name in a variable. After searching around I thought the following approach would work but I still get the "type does not support indexing" error. This example is simplified:

type item struct {
red   bool
green bool
blue  bool
}

func (i *item) setProperty (propName string, propValue bool) *item {
(*i)[propName] = propValue
return i
}

func main() {
item := &item{red: true, green: true}
item = item.setProperty("blue", true)
fmt.Println(item)
}

Is it possible to assign to struct fields where the field name is in a variable? Any suggestions on how I get that to work? Thank you.


Ian Lance Taylor

unread,
May 21, 2021, 5:47:42 PM5/21/21
to Jay Adams, golang-nuts
On Fri, May 21, 2021 at 2:38 PM Jay Adams <t208...@gmail.com> wrote:
>
> Is it possible to assign to struct fields where the field name is in a variable? Any suggestions on how I get that to work? Thank you.

In Go this is done using type reflection.

https://play.golang.org/p/7Wt8eczIeXO

Ian
Reply all
Reply to author
Forward
0 new messages