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).
Some people say that Go's interfaces are dynamically typed, but that is misleading. They are statically typed: a variable of interface type always has the same static type, and even though at run time the value stored in the interface variable may change type, that value will always satisfy the interface.
Golang allows to also pass interface type. It checks if the dynamic value satisfies desired interface and returns value of such interface type value. In contract to conversion, method set of interface passed to type assertion doesn’t have to be a subset of v ’s type method set ( source code ): v2, ok := v1. (I2)
The syntax for general type casting is pretty simple. just use that other type name as a function to convert that value. e.g. i := int (32.987) // casting to integer Unlike other languages, Go doesn’t support implicit type conversion. Although when dividing numbers, implicit conversions happen depending on the scenario.
Type conversion is a great way to change the original data type. But unfortunately, in some cases, it loses precision. It should be done sparingly. The needs of type conversion lie in the fact Go doesn’t support implicit type conversions. So in many cases, it should be done separately.
No you can't. Go is a static typed language. The type of a variable is determined at compile time.
If you want to determine dynamically the type
of an interface{}
you could use type switching:
var t interface{} t = functionOfSomeType() switch t := t.(type) { default: fmt.Printf("unexpected type %T", t) // %T prints whatever type t has case bool: fmt.Printf("boolean %t\n", t) // t has type bool case int: fmt.Printf("integer %d\n", t) // t has type int case *bool: fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool case *int: fmt.Printf("pointer to integer %d\n", *t) // t has type *int }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With