Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading