Search code examples
gostructure

Get structure field by string in Goland


In JS i can just:

const str = "Name"
const obj = {"Name" : "SomeName"}
console.log(obj[str])

How i can do this in GoLand?


Solution

  • Typically, you don't do this with structs in Go. When you need to be able to do this, the best way is usually to create a map[string]string first, which you can access the same way as in JS. Then you convert it into a struct with code like

    structFromMap := myStructType{
     Name: myMap["Name"], 
     FavoritePokemon: myMap["FavoritePokemon"],
    }
    

    If you really need to interact with a struct this way, you can import the "reflect" package and then do

    reflect.ValueOf(myStruct).FieldByName("Name")