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.

2
  • 1
    You're missing the point of a statically typed language. Commented Jun 19, 2014 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. Commented Dec 13, 2022 at 1:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

Ok, and at compile time?
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.
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.
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., stackoverflow.com/questions/19759274/…) And we'll give it a shot, though it might not be concise as it would be in Python.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.