Type casting in Golang;
Type casting refers to changing the value of one data type to another.
Type casting for Primitives
Primitive type casting is simple and easy when you follow the below pattern,
TypeToCastTo(Value)
For example, consider the below program where we cast an int type to float32 type,
func TypeCast() { var intType int = 32 var float32Type float32 = float32(intType) fmt.Println(float32Type)}
Type casting for Objects
Sometimes you may need to type cast an object when you get their value, say from a Map. The following scenario illustrates adding different data type values to a map and then retrieving it and typecasting to read the object values,
type Sample struct { name string}func TypeCast() { var myMap = make(map[string]interface{}) myMap["Key1"] = "Value1" myMap["Key2"] = &Sample{ name: "Value2", }
for k, _ := range myMap { if typeVal, ok := findType(myMap[k]); ok { fmt.Println(typeVal) } }}func findType(val interface{}) (typeVal string, ok bool) { switch val.(type) { case string: return "String", true case *Sample: return "Sample", true } return "", false}
In the above code, I have a map of type map[stringinterface{}
, which can store value of any type. I have stored a string
as well as Sample struct
type in the map.
findType(val interface{}) (typeVal string, ok bool)
method determines the type of the value stored in the map by using a simple switch
statement. Note that we can use the direct string
type in the case for comparing the string data type, but for the struct *
it is a pointer.
These typecasting techniques are very useful while writing code in golang. Hope they are helpful.