gpt4 book ai didi

reflection - 反射(reflect) : How to get the name of a struct field?

转载 作者:IT王子 更新时间:2023-10-29 02:34:06 25 4
gpt4 key购买 nike

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"

这在 Go 中可能吗?我希望拥有尽可能少的“魔术弦”,所以不要

UpdateFields("姓名", "密码")

我更愿意使用

UpdateFields(user.Name, user.Password)

最佳答案

你不能那样做。我能想到的最接近的东西,但它太丑了所以不要把它当作答案是这样的:

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

关于reflection - 反射(reflect) : How to get the name of a struct field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29967157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com