4

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.

Bndr
  • 317
  • 5
  • 13
  • 1
    You're missing the point of a statically typed language. – OneOfOne Jun 19 '14 at 20:07
  • @OneOfOne The getattr and call methods have nothing to do with static typing. The first is related to introspection, and the second is a way of treating an object as a function so it can be "called" as though it was a function. The builtin `reflect` package can be used to get exported attributes. I don't know of an equivalent to the call method in Go, but I don't think you it is essential: just create an anonymous function that includes a ref to the object and pass that function instead of the object. – Oliver Dec 13 '22 at 01:47

2 Answers2

8

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Ok, and at compile time? – Bndr Jun 19 '14 at 15:45
  • 4
    What does that mean ? You can preprocess your code to augment it of course, and Go contains static analysis and transformation tools, but it's clear that you're facing a [xy problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Denys Séguret Jun 19 '14 at 15:47
  • If OP just wants to wrap access to members (for example for logging or access control), it can be done with reflection. Though I highly suggest against it. – Not_a_Golfer Jun 19 '14 at 16:05
  • Go isn't the sort of language you're expecting--your main dynamic tools are interfaces and embedding here. The sort of question we can answer is more like "I want to build an app that does XYZ and can't think of any way to do it in Go." (e.g., http://stackoverflow.com/questions/19759274/sort-points-structs-by-different-dimensions-in-go-lang) And we'll give it a shot, though it might not be concise as it would be in Python. – twotwotwo Jun 19 '14 at 17:36
8

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.

warvariuc
  • 57,116
  • 41
  • 173
  • 227