在Goland中通过字符串获取结构字段

huangapple go评论84阅读模式
英文:

Get structure field by string in Goland

问题

在GoLand中,你可以使用以下代码来实现相同的功能:

package main

import "fmt"

func main() {
    str := "Name"
    obj := map[string]string{"Name": "SomeName"}
    fmt.Println(obj[str])
}

这段代码创建了一个名为str的字符串变量和一个名为obj的映射(map)变量。然后,通过obj[str]来访问映射中的值,并使用fmt.Println打印出来。

英文:

In JS i can just:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

How i can do this in GoLand?

答案1

得分: 2

通常,在Go语言中不会这样做。当你需要这样做时,通常最好的方法是首先创建一个map[string]string,你可以像在JavaScript中一样访问它。然后,你可以使用以下代码将其转换为结构体:

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

如果你真的需要以这种方式与结构体交互,你可以导入reflect包,然后执行以下操作:

reflect.ValueOf(myStruct).FieldByName("Name")
英文:

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[&quot;Name&quot;], 
 FavoritePokemon: myMap[&quot;FavoritePokemon&quot;],
}

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

reflect.ValueOf(myStruct).FieldByName(&quot;Name&quot;)

答案2

得分: 1

package main

import (
	"fmt"
	"reflect"
)

func main() {
	type user struct {
		firstName string
		lastName  string
	} // 在这里定义你的结构体

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

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

为了帮助你开始学习Go语言,我推荐你阅读这个网站:https://quii.gitbook.io/learn-go-with-tests/

祝你学习和编码愉快 在Goland中通过字符串获取结构字段

英文:
package main

import (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

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

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

	fmt.Println(&quot;Name:&quot;, s.FieldByName(&quot;firstName&quot;))
}

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

Have a good study/code 在Goland中通过字符串获取结构字段

答案3

得分: 1

你可以在Golang中使用映射(mapping):

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

这段代码使用了映射(mapping)来获取键为"name"的值。

英文:

kindly, You can use mapping in golang:

str:= &quot;name&quot;
obj := map[string]interface{}{
   &quot;name&quot;: &quot;someName&quot;,
}
fmt.printLn(obj[str])

huangapple
  • 本文由 发表于 2022年9月6日 04:11:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73614249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定