Home > Mobile >  Get structure field by string in Goland
Get structure field by string in Goland

Time:09-06

In JS i can just:

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

How i can do this in GoLand?

CodePudding user response:

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

CodePudding user response:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    type user struct {
        firstName string
        lastName  string
    } // hire you define your struct

    u := user{firstName: "John", lastName: "Doe"}
    s := reflect.ValueOf(u)

    fmt.Println("Name:", s.FieldByName("firstName"))
}

To help u started in Go I recommend this: https://quii.gitbook.io/learn-go-with-tests/

Have a good study/code :)

CodePudding user response:

kindly, You can use mapping in golang:

str:= "name"
obj := map[string]interface{}{
   "name": "someName",
}
fmt.printLn(obj[str])
  • Related