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.

0

1 Answer 1

9

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).

Sign up to request clarification or add additional context in comments.

4 Comments

I think there's also the option of don't. Always pretty dangerous to just directly transpile code
@Zak: I don't understand your comment. Who's transpiling code?
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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.