Dynamically Add Attributes to a Go Struct at Runtime
Posted May 13, 2023 by Rohith ‐ 1 min read
There are some workarounds to dynamically add attributes to a go struct at the Runtime. One way to achieve this is by using a map to store the attributes of a struct. Another way to achieve similar functionality is by using reflection.
On this page
Using Map
One way to achieve this is by using a map to store the attributes of a struct. Here’s an example:
type MyStruct struct {
Attributes map[string]interface{}
}
func main() {
myStruct := MyStruct{Attributes: make(map[string]interface{})}
myStruct.Attributes["attr1"] = "value1"
myStruct.Attributes["attr2"] = 123
}
In this example, we define a MyStruct
type that has a map
named Attributes
as its field. We can then dynamically add attributes to the struct by adding key-value pairs to the Attributes
map.
Using Reflection
Another way to achieve similar functionality is by using reflection. Here’s an example:
import (
"reflect"
)
type MyStruct struct {
Attr1 string
}
func main() {
myStruct := MyStruct{}
value := reflect.ValueOf(&myStruct).Elem()
value.FieldByName("Attr2").SetString("value2")
}
In this example, we define a MyStruct
type that has an Attr1
field. We can then dynamically add a new attribute named Attr2
to the struct by using reflection to set its value.
Note that both of these solutions have some limitations and trade-offs. Using a map to store the attributes can lead to less efficient code and more complex logic, while using reflection can make the code harder to read and maintain. Therefore, it’s important to carefully consider the requirements and constraints of the problem before choosing a solution.