5 minutes read

Fun fact: in Go, it is not allowed to perform mathematical operations on mixed numeric types. However, if you convert these types to one single numeric type, you will have no issues with using operations over numbers. In this case, the knowledge of type casting and type switching would be handy. Type casting (type conversion) in Go is a method of converting the type of data from one to another. Type switching, on the other hand, is a way of asserting multiple types in sequence and getting the type of the interface. This topic will focus on the ways to perform type conversion and type switching in Go.

How to do type casting

Suppose you are designing a Simple Calculator project. You have two inputs: the first one is an integer, the second one is a float, and the desired output is the sum of these numbers.

var number1 int32 = 56
var number2 float32 = 127.5

You assign the result of the addition to a new variable and print it.

number3 := number1 + number2
fmt.Println(number3)

However, intriguingly, Go says it is impossible and returns an error. The message is the following:

invalid operation: number1 + number2 (mismatched types int32 and float32)

It happens because in Go, you can perform operations only over the variables of the same type; otherwise, you get an error. Type casting is the way to solve this. Use the following syntax to achieve it:

newVariable := Type(convertedVariable)

You have a variable (convertedVariable) that you want to convert to another type (Type). In the example above, you know that the result of the addition of number1 and number2 will be a float; therefore, you should convert number1 from int32 to float32:

number1Converted := float32(number1)

Now, if you add these numbers and print the result like this:

number3 := number1Converted + number2
fmt.Println(number3)

// Output:
// 183.5

You will get the output of 183.5.

How to do type assertion

Before you start type switching, it's important to understand type assertion. Type assertion is a way of getting access to the interface's value. As the name suggests, by type assertion, you assert that a variable has some type. Saying so, type assertion doesn't allow changing the interface's data type.

Let's say you have an interface v with the value Golang.

var v interface{} = "Golang"

You can access the interface's concrete value in the following way:

s, ok := object.(type)

object in this case is v, and the type is a string. If you then print s and ok, you will get the following result:

s, ok := v.(string)
fmt.Println(s, ok)

// Output:
// Golang true

Let's review what happens here. First, you created v, which is of the inteface{} type. Then, you assigned a string type to it, making v actually a string. During the assertion, you should check whether you are asserting a type correctly or not. Therefore, type assertion returns two values. Here, s is the value of the interface, and ok is the result of the assertion check. It returns true if the assertion is done correctly and false otherwise; to further illustrate this, let's look at an example of an incorrect type assertion:

s, ok := v.(int)
fmt.Println(s, ok)

// Output:
// 0 false

Interestingly, you can ignore the ok variable in the above code snippets since using it in every type of assertion is unnecessary. Having a variable s would be enough. For example, s := object.(type) will work similarly without error. Only the value of the interface would be assigned to the s variable. One thing to note is that if it is impossible to do the assignment, then Go will raise panic.

Type switching

Type switching does a couple of type assertions in a row and returns the one that matches the type. It is used when you are not sure about the type of interface.

For example, let's continue working with the interface v. Right now, you are unsure about the type and want to print the data type of the interface's value. You can do this with type switching:

switch v.(type) {
case nil:
   fmt.Println("v is a nil type")
case int:
   fmt.Print("v is an int type")
case string:
   fmt.Println("v is a string type")
default:
   fmt.Println("type is not defined")
}

// Output:
// v is a string type

This piece of code will return v is a string type because the value of the interface is of the string type.

Conclusion

If you perform mathematical operations over numerical variables with different data types, the compiler will not allow us to execute the code by raising an error. Type casting helps to solve this. It is a way of changing the type of a variable. Type switching is a method of identifying the type of an interface.

  • To perform type casting, you can use the following formulation: Type(Variable), where Type is the type to which we are converting, and Variable is the variable or its value requiring type conversion.

  • Type assertion is a way to check a variable's type. The expression of assertion usually returns two values: the concrete value of the interface and the result of checking the correctness of the assertion. If you are confident the type assertion has been done correctly, you can omit the second value. Therefore, it is optional. However, in case of any doubts about the type of interface, you can check it using type switching.

19 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo