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

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

reflect: How to get the name of a struct field?

问题

以下是翻译好的内容:

  1. type User struct { Name string }
  2. func test(o interface{}) {
  3. t := reflect.TypeOf(o)
  4. fmt.Println(t)
  5. }
  6. u := &User{"Bob"}
  7. test(u.Name) // 输出 "string",但我需要 "Name"
  8. Go语言中是否可能实现这个需求我希望尽量减少使用 "magic strings"所以不想使用
  9. `UpdateFields("Name", "Password")`
  10. 而是更愿意使用
  11. `UpdateFields(user.Name, user.Password)`
英文:
  1. type User struct { Name string }
  2. func test(o interface{}) {
  3. t := reflect.TypeOf(o)
  4. fmt.Println(t)
  5. }
  6. u := &User{"Bob"}
  7. 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

你不能这样做。我能想到的最接近的方法是这样的,但是它非常丑陋,所以不要把它当作答案

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type Foo struct {
  7. Bar string
  8. Baz int
  9. }
  10. var Foo_Bar = reflect.TypeOf(Foo{}).Field(0).Name
  11. var Foo_Baz = reflect.TypeOf(Foo{}).Field(1).Name
  12. func main() {
  13. fmt.Println(Foo_Bar, Foo_Baz)
  14. }
英文:

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:

  1. package main
  2. import(
  3. "fmt"
  4. "reflect"
  5. )
  6. type Foo struct {
  7. Bar string
  8. Baz int
  9. }
  10. var Foo_Bar = reflect.TypeOf(Foo{}).Field(0).Name
  11. var Foo_Baz = reflect.TypeOf(Foo{}).Field(1).Name
  12. func main(){
  13. fmt.Println(Foo_Bar, Foo_Baz)
  14. }

答案2

得分: 1

你可以通过定义一个基于字符串的新类型,并在结构体内部使用该类型作为类型来实现这个功能:

  1. package main
  2. import "fmt"
  3. import "reflect"
  4. type Name string
  5. type User struct {
  6. Name Name
  7. }
  8. func test(o interface{}) {
  9. t := reflect.TypeOf(o)
  10. fmt.Println(t.Name())
  11. }
  12. func main() {
  13. u := &User{"Bob"}
  14. test(u.Name) // 输出 "Name"
  15. test("Tim") // 输出 "string"
  16. }

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:

  1. package main
  2. import "fmt"
  3. import "reflect"
  4. type Name string
  5. type User struct {
  6. Name Name
  7. }
  8. func test(o interface{}) {
  9. t := reflect.TypeOf(o)
  10. fmt.Println(t.Name())
  11. }
  12. func main() {
  13. u := &User{"Bob"}
  14. test(u.Name) // Prints "Name"
  15. test("Tim") // Prints "string"
  16. }

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:

确定