英文:
Golang equivalent of pythons __getattr__() or __call__()
问题
我想在运行时操作结构体。
例如,我有一个结构体:
type Item struct {
SomeField string
}
是否可以在运行时添加字段?或者访问尚未定义的属性。类似于Python中的__getattr__()
或__call__()
,这样我就可以动态控制访问的字段/方法。
例如,像这样做一些操作:
Item.DynamicField
或 Item.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语言的启发(getattr
、setattr
、hasattr
等),并提供了对结构字段和标签的简化访问。你可以在这里找到该包的代码: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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论