dongxuan2015 2015-04-30 11:56
浏览 24
已采纳

反映:如何获取结构域的名称?

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)

  • 写回答

2条回答 默认 最新

  • doujindou4356 2015-04-30 12:25
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路