英文:
reflect: How to get the name of a struct field?
问题
以下是翻译好的内容:
type User struct { Name string }
func test(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(t)
}
u := &User{"Bob"}
test(u.Name) // 输出 "string",但我需要 "Name"
在Go语言中是否可能实现这个需求?我希望尽量减少使用 "magic strings",所以不想使用
`UpdateFields("Name", "Password")`
而是更愿意使用
`UpdateFields(user.Name, user.Password)`
英文:
type User struct { Name string }
func test(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(t)
}
u := &User{"Bob"}
test(u.Name) // prints "string", but I need "Name"
Is this possible in Go? I want to have as few "magic strings" as possible, so instead of having
UpdateFields("Name", "Password")
I'd much rather use
UpdateFields(user.Name, user.Password)
答案1
得分: 3
你不能这样做。我能想到的最接近的方法是这样的,但是它非常丑陋,所以不要把它当作答案:
package main
import (
"fmt"
"reflect"
)
type Foo struct {
Bar string
Baz int
}
var Foo_Bar = reflect.TypeOf(Foo{}).Field(0).Name
var Foo_Baz = reflect.TypeOf(Foo{}).Field(1).Name
func main() {
fmt.Println(Foo_Bar, Foo_Baz)
}
英文:
You can't do that. The closest thing I can think of, but it's damn ugly so do not take it as the answer is something like this:
package main
import(
"fmt"
"reflect"
)
type Foo struct {
Bar string
Baz int
}
var Foo_Bar = reflect.TypeOf(Foo{}).Field(0).Name
var Foo_Baz = reflect.TypeOf(Foo{}).Field(1).Name
func main(){
fmt.Println(Foo_Bar, Foo_Baz)
}
答案2
得分: 1
你可以通过定义一个基于字符串的新类型,并在结构体内部使用该类型作为类型来实现这个功能:
package main
import "fmt"
import "reflect"
type Name string
type User struct {
Name Name
}
func test(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(t.Name())
}
func main() {
u := &User{"Bob"}
test(u.Name) // 输出 "Name"
test("Tim") // 输出 "string"
}
英文:
You can make this work by defining a new type that is based off of string, and use that as the type inside of your struct:
package main
import "fmt"
import "reflect"
type Name string
type User struct {
Name Name
}
func test(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(t.Name())
}
func main() {
u := &User{"Bob"}
test(u.Name) // Prints "Name"
test("Tim") // Prints "string"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论