6

For reference: example here

I am trying to access a struct field using a variable key, to explain in PHP you can do the below.

$arr = ["test" => "foo"];
$key = "test";
$result = $arr[$key];

Or in Javascript you can do the below

const obj = {"test": "foo"}
const key = "test"
const result = obj[key]

Is this possible with go structs? I have searched for this functionality, but the answers always seem to point to the reflect package and running a for loop over the struct fields.

My code (linked above) gets the compile error of invalid operation: p[key] (type Post does not support indexing) which makes sense, but I can't find a way around this.

5
  • 3
    You would use reflection for it. But the whole idea looks dirty and unreasonable: you should always know what fields are available and how to access them. Commented Mar 21, 2018 at 23:17
  • I think I understand your use-case (supporting a requirement to update just one part of an existing post). You could do something a little yuck- marshal the existing post into JSON and then into a map[string]string; if you did the same with the updated data, you could iterate through the updated data (which would have only one key), update that key in the map that represents the existing post and marshal that back into JSON and then unmarshal it into the post struct haha Commented Mar 21, 2018 at 23:56
  • 2
    Don't try to program PHP or JavaScript in Go; that will just cause pain. Either use a map, or access struct fields by their (static) name. Commented Mar 22, 2018 at 0:35
  • 1
    This code is of course going no where near production, I'm just trying to solidify my learning. If it's not directly possible and you'd need to iterate over a map then this answers my question. Thanks all! Commented Mar 22, 2018 at 6:47
  • See stackoverflow.com/questions/18930910/… Commented May 30, 2023 at 11:19

1 Answer 1

8

One of the main points when using structs is that the way how to access the fields is known at compile time.Then the produced code uses fixed indexes added to a base address of the struct.

For any kind of dynamism here you just need to use map[string]string or similar.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.