Golang中与Python的__getattr__()或__call__()等效的方法是什么?

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

Golang equivalent of pythons __getattr__() or __call__()

问题

我想在运行时操作结构体。

例如,我有一个结构体:

type Item struct {
    SomeField string
}

是否可以在运行时添加字段?或者访问尚未定义的属性。类似于Python中的__getattr__()__call__(),这样我就可以动态控制访问的字段/方法。

例如,像这样做一些操作:
Item.DynamicFieldItem.DynamicMethod(),其中我不知道将要访问/调用的字段或方法,所以无法静态定义它。

也许我在反射包中遗漏了一些东西?

谢谢。

英文:

I would like to manipulate structs at Runtime.

For example, I have a struct:

type Item struct {
 SomeField string
}

Is it possible to add field on runtime? Or Access Attribute that is not yet defined. Something like pythons __getattr__() or __call__() so I could dynamically control the fields/methods accessed.

E.g. do something like
Item.DynamicField or Item.DynamicMethod() where I don't know exactly the Field or the Method that will be accessed/called, So I can't define it statically.

Maybe I'm missing something in the Reflect package?

Thank you.

答案1

得分: 8

在Go语言中,无法在运行时添加字段或访问尚未定义的属性。Go是一种编译语言,具有静态定义的类型。如果你想要动态添加属性,可能需要使用map(映射)。

英文:

> Is it possible to add field on runtime? Or Access Attribute that is not yet defined.

No. Go is a compiled language with statically defined types. You probably need a map if you want to dynamically add properties.

答案2

得分: 8

reflections包的目的是在运行时帮助开发人员更轻松地反射结构。它的API受到Python语言的启发(getattrsetattrhasattr等),并提供了对结构字段和标签的简化访问。你可以在这里找到该包的代码:https://github.com/oleiade/reflections

英文:

https://github.com/oleiade/reflections
> The purpose of reflections package is to make developers life easier
> when it comes to introspect structures at runtime. Its API is inspired
> from python language (getattr, setattr, hasattr...) and provides
> a simplified access to structure fields and tags.

huangapple
  • 本文由 发表于 2014年6月19日 23:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/24310713.html
匿名

发表评论

匿名网友

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

确定