以字符串开头的结构字段名称

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

Struct field names starting with a string

问题

我有一个Go结构体,并且我需要使用其中一个字段。然而,我现在只有一个字符串。我该如何将其转换为字段本身?

package main
import "fmt"

func main() {

    type Point struct{
        x int
        y int
    }

    pt := Point{x:2, y:3}
    a  := "x"
    fmt.Printf("%d", pt.a)
}

由于a = "x",我期望输出为pt.x = 2。这是它打印出的错误信息:

$ go run point.go
# command-line-arguments
./point.go:14: pt.a undefined (type Point has no field or method a)

请注意,pt.a是无效的,因为Point结构体没有名为a的字段或方法。要动态访问结构体字段,可以使用反射机制。你可以使用reflect包来实现这一点。以下是一个示例:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	type Point struct {
		x int
		y int
	}

	pt := Point{x: 2, y: 3}
	fieldName := "x"

	value := reflect.ValueOf(pt)
	field := value.FieldByName(fieldName)

	if field.IsValid() {
		fmt.Printf("%s: %d\n", fieldName, field.Int())
	} else {
		fmt.Printf("Field %s not found\n", fieldName)
	}
}

这将输出:

x: 2

这样你就可以根据字段名动态获取结构体字段的值了。

英文:

I have a go struct and I need to work with one of the fields. However I am starting with a string. How do I case it to get the field itself.

package main
import "fmt"

func main() {

	type Point struct{
  x int
  y int
}

	pt := Point{x:2, y:3}
	a  := "x"
	fmt.Printf("%s", pt.a)
} 

Since a = "x" I am expecting pt.x = 2. Here's the error message it prints out. I am definitely starting with a string so I can't just remove the quotation marks.

$ go run point.go
# command-line-arguments
./point.go:14: pt.a undefined (type Point has no field or method a)

答案1

得分: 3

如果您需要访问一个以字符串形式给出名称的字段,您别无选择,只能使用反射。Go语言不像Python那样简单。:-)

这篇博客有一个很好的解释。

这里是反射包的文档。

但请注意,反射通常只应作为最后的选择。它会移除静态类型安全,并且对性能有害。

您真正需要什么?可能有一种方法可以满足您的需求而不使用反射。例如,如果您不需要将方法附加到结构体上,您可以使用map[string]int

英文:

If you need to access a field whose name is given as a string, you have no choice but to use reflection. Go ain't Python. 以字符串开头的结构字段名称

This blog has a nice explanation.

Here is the reflect package documentation.

But note that reflection should usually be used as a last resort only. It removes the static type safety and is detrimental for performance.

What are you really looking for? There may be a way to address your requirements without using reflection. For example, if you don't need methods attached to your struct, you could use map[string]int.

huangapple
  • 本文由 发表于 2015年10月25日 22:29:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/33330814.html
匿名

发表评论

匿名网友

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

确定