I would like to know if it's possible to change the type of variable in run time, for example:
package main
import "github.com/fatih/structs"
type T struct {
MyField bool
}
func main() {
fakeVariable := ""
s := structs.New(T{})
for _, field := range s.Fields() {
field.Set(fakeVariable)
}
}
Since MyField is a boolean, I would like to change fakeVariable to a boolean, and the expected result would be that MyField
is false (because empty strings are false). But the MyField type could be anything, so I would like to know how to cast it to the type of MyField. I know that I can get the field type using field.Kind()
, and this:
field.Set(fakeVariable.(field.Kind())
Won't work.
The fakeVariable
will be always a string, but it could hold the value "10.0", and if the type of MyField is float
, it should cast to float, but if its string, it should only assign it. Make sense?
Any ideas if what I'm trying is possible?
How to change type of variable in runtime
You cannot.