3

I am new to golang and migrating from php to golang.

I am trying to do something like below stuff, where I want field name age to get assigned from variable test. Is this possible in golang?

In php, we have provision like $$test, looking something similar in golang as well.

 package main
 import "fmt"
 // This `person` struct type has `name` and `age` fields.
 type person struct {
   name string
   age  int
 }

 func main() {

   var test = "age"     
   fmt.Println(person{name: "Alice",test: 30})

 } 

This is just sample code replicating my use case.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
RKP
  • 750
  • 2
  • 12
  • 23

1 Answers1

8

You have three options, in rough order of preference:

1) An if/switch statement:

var p = &person{}
if key == "age" {
    p.age = value
}

2) Use a map instead of a struct:

var p = map[string]interface{}
p[key] = value

3) Use reflection. See this question for details, but generally you should avoid reflection. It's slow, and non-idiomatic, and it only works with exported fields (your example uses un-exported fields, so as written, is not a candidate for reflection anyway).

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • I think there's also the option of don't. Always pretty dangerous to just directly transpile code – Zak Jul 09 '18 at 09:12
  • @Zak: I don't understand your comment. Who's transpiling code? – Jonathan Hall Jul 09 '18 at 09:31
  • Sorry, that wasn't super clear; I read this part of the question "and migrating from php to golang." as if it were a copy paste job. I was just suggesting that sometimes the "way things are done" is different in different langauges, and there's no "golang way to do" a specific PHP pattern. (potentially unhelpful comment ^^). Maybe the root of the problem would suggest a different solution; rather than, how do I do this in go? – Zak Jul 09 '18 at 09:34
  • 1
    @Zak: I think I understand. There are still times in Go, when you want to update a struct based on a string value, so I don't think it's fair to say "never do this"--although perhaps in the OP's specific situation, there is a useful alternative. – Jonathan Hall Jul 09 '18 at 09:38