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.

Sam White
  • 125
  • 3
  • 10
  • 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. – zerkms Mar 21 '18 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 – initialed85 Mar 21 '18 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. – Peter Mar 22 '18 at 00: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! – Sam White Mar 22 '18 at 06:47
  • See https://stackoverflow.com/questions/18930910/access-struct-property-by-name – Dovev Hefetz May 30 '23 at 11:19

1 Answers1

7

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.

Wojciech Kaczmarek
  • 2,173
  • 4
  • 23
  • 40