反思:如何获取struct字段的名称?

时间:2015-04-30 11:56:40

标签: reflection go

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("Name", "Password")

我更愿意使用

UpdateFields(user.Name, user.Password)

2 个答案:

答案 0 :(得分:2)

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

[self setTitle:@"MyTitle"];

答案 1 :(得分: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) // Prints "Name"
    test("Tim") // Prints "string"
}

Playground

相关问题