反射:如何获取结构体字段的名称?

huangapple go评论79阅读模式
英文:

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

Playground

英文:

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

Playground.

huangapple
  • 本文由 发表于 2015年4月30日 19:56:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/29967157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定