Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: cast an interface to a typed variable dynamically

Tags:

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).

like image 259
orcaman Avatar asked Jan 15 '15 19:01

orcaman


People also ask

Are interfaces in Golang dynamically typed?

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.

How to pass interface type in type assertion in Golang?

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)

How to cast int to integer in Golang?

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.

What is type conversion in Golang?

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.


1 Answers

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 typeof 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 } 
like image 173
fabrizioM Avatar answered Oct 12 '22 03:10

fabrizioM