按名称访问结构属性 [英] Access struct property by name

查看:66
本文介绍了按名称访问结构属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 包主
导入fmt

类型顶点结构{
X int
Y int
}

func main(){
v:= Vertex {1, 2}
fmt.Println(getProperty(& v,X))
}

func getProperty(v * Vertex,property string)(string){
return v [property]
}

错误: prog .go:18:无效操作:v [property](索引类型* Vertex)



我想要访问Vertex X财产使用其名称。如果我做了 v.X ,它可以工作,但是 v [X] 不会。



有人能告诉我如何使这项工作成功吗?

大多数代码不应该需要这种动态查找。与直接访问相比,它效率低下(编译器知道Vertex结构中X字段的偏移量,它可以将v.X编译为单个机器指令,而动态查找则需要某种类型的哈希表实现或类似的操作)。它也禁止静态类型输入:编译器无法检查你是否试图动态访问未知字段,也无法知道结果类型应该是什么。



但是...这种语言提供了一个体现模块,可以满足您需要的罕见时间。

 包主要

导入fmt
导入反映

类型顶点struct {
X int
Y int
}

func main(){
v:=顶点{1,2}
fmt。 println(getField(& v,X))
}

func getField(v *顶点,字符串)int {
r:= reflect.ValueOf(v)
f:= reflect.Indirect(r).FieldByName(field)
return int(f.Int())
}

这里没有错误检查,所以如果你要求一个不存在的字段,或者这个字段不是int类型的话,你会感到恐慌。查看反映的文档了解更多详情。


Here is a simple go program that is not working :

package main
import "fmt"

type Vertex struct {
    X int
    Y int
}

func main() {
    v := Vertex{1, 2}
    fmt.Println(getProperty(&v, "X"))
}

func getProperty(v *Vertex, property string) (string) {
    return v[property]
}

Error: prog.go:18: invalid operation: v[property] (index of type *Vertex)

What I want is to access the Vertex X property using its name. If I do v.X it works, but v["X"] doesn't.

Can someone tell me how to make this work ?

解决方案

Most code shouldn't need this sort of dynamic lookup. It's inefficient compared to direct access (the compiler knows the offset of the X field in a Vertex structure, it can compile v.X to a single machine instruction, whereas a dynamic lookup will need some sort of hash table implementation or similar). It's also inhibits static typing: the compiler has no way to check that you're not trying to access unknown fields dynamically, and it can't know what the resulting type should be.

But... the language provides a reflect module for the rare times you need this.

package main

import "fmt"
import "reflect"

type Vertex struct {
    X int
    Y int
}

func main() {
    v := Vertex{1, 2}
    fmt.Println(getField(&v, "X"))
}

func getField(v *Vertex, field string) int {
    r := reflect.ValueOf(v)
    f := reflect.Indirect(r).FieldByName(field)
    return int(f.Int())
}

There's no error checking here, so you'll get a panic if you ask for a field that doesn't exist, or the field isn't of type int. Check the documentation for reflect for more details.

这篇关于按名称访问结构属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆