In Go, is it possible to cast variables dynamically somehow?
For example, if a simple cast would be:
var intAge = interfaceAge.(int)
What if I do not know that age is an int in advance? A simple way of writing it would be
var x = getType()
var someTypeAge = interfaceAge.(x)
Is there a way of achieving something like this? The reflect package gives some ways of determining or casting a type at runtime - but I couldn't find anything like the above mentioned (a generic scheme that would work for all types).
x
has? Go is a language with static types. The type of a variable is always known at compile time. The type of a variable might be an interface type though. – Buzzardfoo
is an interface type, you can dox := foo.(int)
(or more generallyfoo.(T)
. It's a type assertion and it will panic at runtime if the interface doesn't hold the asked for type. You can usex, ok := foo.(int)
where x will be the zero value andok
will be false if the type assertion failed. – OswinsomeTypeAge := interfaceAge
. You can pass around data of typeinterface{}
to your heart's content -- and certain functions, such asfmt.Println(interfaceAge)
, will dynamically process the data. – Alluvion