英文:
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 = "Name"
const obj = {"Name" : "SomeName"}
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["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")
答案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/
祝你学习和编码愉快
英文:
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
答案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:= "name"
obj := map[string]interface{}{
"name": "someName",
}
fmt.printLn(obj[str])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论