Type Casting in Golang

Learn via video courses
Topics Covered

Overview

Type cast in golang is used to change a variable's data type. If you want to save a decimal value as a simple integer, you can typecast float to int, for instance. Values of one type can be transformed into another using the cast operator.

Type Cast in Golang

The process of changing an integer, float, or string value to another data type is known as type casting. For instance,

Here, the expression int(floatValue) indicates that we are changing the float value 9.8 to 9.

Explicit type casting is used in Go for this situation because the type conversion is being done explicitly.

Type conversion is assigning a value from one data type to another. Java and C/C++ are statically typed languages offering implicit type conversion. Golang, however, is special. Even if the data types are compatible, it does not permit implicit or automatic type conversion. This is because Golang's Strong Type System restricts it. Type conversions must be made clearly.

Types in Go

There are many different data kinds in Go. Examples of data types include numbers, floating points, booleans, and strings.

  1. Number: int, int32, int64, uint32, uint64 etc
  2. Floating Points: float32, float64, complex64, complex128
  3. Boolean: bool
  4. String: string

Type Cast in Golang Syntax

General type casting has a simple syntax. To convert that value, simply use that other type name as a function.

Implicit Type Conversion in Go

Implicit type casting is the automatic conversion of one data type to another. However, implicit type casting is not supported by Go. For instance,

We created a number-named int type variable in the example above. Here, we're trying to give the int variable the floating-point value 4.34.

An error will appear when we execute this program:

Explicit Type Conversion in Go

Golang provides a number of built-in functions for doing explicit type casting, including int(), float32(), string(), and others.

Let's look at a few instances of explicit type casting:

Example: Go float to int conversion

Output

Here, we have used the function int() to convert the value from 5.45 to 5.

In this instance, we are manually converting the type of one type to another. Therefore, it is known as explicit type casting.

Example: Go float to int Conversion

In Go, you can convert a float64 to an int by simply casting the float64 value to an int. Here's an example:

Output:

In this example:

  1. We define a floatNum variable with a float64 value of 12.345.
  2. We convert the floatNum to an int by simply assigning it to an intNum variable. Go will automatically perform the conversion, truncating the decimal part.
  3. Finally, we print both the original float and the converted int values.

Keep in mind that when you convert a float64 to an int, the fractional part of the floating-point number is discarded, and the resulting int will only contain the integer part of the value.

Example: Go int to float Conversion

In Go, you can convert an int to a float64 by explicitly casting the int value to a float64. Here's an example:

Output:

In this example:

  1. We define an intNum variable with an integer value of 42.
  2. We convert the intNum to a float64 by explicitly casting it as float64(intNum). This casting operation converts the integer into a floating-point number.
  3. Finally, we print both the original integer and the converted float values.

When converting an int to a float64, Go performs the conversion without losing any precision, and the resulting float64 will contain the same numeric value as the original integer.

Example: Add int and float Number Using Go Type Casting

To add an integer and a floating-point number in Go, you need to cast the integer to a floating-point type before performing the addition. Here's an example:

Output:

In this example:

  1. We define an integer intValue with a value of 5 and a float64 floatValue with a value of 3.14.
  2. We cast the integer intValue to a float64 using float64(intValue) before performing the addition.
  3. We add the two numbers and store the result in the result variable.
  4. Finally, we print the original integer, float, and the sum of the two numbers as a float.

This allows you to perform addition between different numeric types in Go by first casting them to a compatible type.

FAQs

Q. How do you convert types of Go?

A. In Go, you can convert between different types using type casting. Type casting allows you to change the data type of a value or variable explicitly. Here's how you can perform type conversions in Go:

  1. Basic Type Conversion:

    You can perform basic type conversions by explicitly casting the value or variable to the desired type. For example:

    In this example, we cast an integer to a float64.

  2. Type Assertion (for Interfaces):

    Type assertions are used to extract the underlying concrete value from an interface. They are commonly used when working with interface types. For example:

    The second value, ok, is a boolean that indicates whether the conversion was successful or not.

  3. Conversion Functions:

    Some types provide conversion functions to convert between types. For instance, the strconv package provides functions like Atoi and Atof to convert strings to integers and floats, respectively.

    Always handle errors when using conversion functions as they may fail.

  4. Custom Type Conversion:

    You can create custom types in Go and define conversion methods on them. For example:

    In this example, we define a custom type MyInt and a conversion method ToFloat to convert it to a float.

Q. What is type assertion in Golang?

A. In Go, a type assertion is a mechanism used to determine and extract the underlying concrete value from an interface type. It's primarily used when working with interface values, allowing you to access the actual value stored within the interface.

Here's the basic syntax of a type assertion:

  • interfaceValue: An interface value that you want to assert and extract a concrete value from.
  • Type: The type you expect the underlying value to have.
  • value: The variable that will hold the extracted value if the assertion succeeds.
  • ok: A boolean that indicates whether the assertion was successful (true) or not (false).

Here's an example to illustrate type assertion in Go:

In this example:

  1. We declare an interface variable val and assign it the value 42. Since interface{} can hold values of any type, it's not immediately clear what the underlying type is.
  2. We perform a type assertion to check if the underlying type of val is an int. If the assertion is successful, intVal will be assigned the extracted integer value, and ok will be true.
  3. We check the value of ok to determine whether the assertion succeeded or not, and based on that, we print the appropriate message.

Type assertions are handy when you're working with interfaces, as they allow you to work with the concrete types stored within the interface and provide flexibility and type safety when dealing with dynamic data.

Q. How do I change variable type in Golang?

A. In Go, you cannot directly change the type of a variable once it has been declared. Go is a statically typed language, which means that variable types are determined at compile-time and cannot be changed dynamically during program execution.

However, you can create a new variable with the desired type and assign the value of the original variable to it, performing any necessary type conversion in the process. Here's how you can change the variable type in Go:

In this example:

  1. We start with an integer variable myInt with a value of 42.
  2. We create a new variable myFloat of type float64.
  3. We use a type conversion (float64(myInt)) to convert the integer value to a float64 and assign it to myFloat.
  4. Finally, we print the value of myFloat, which is now of type float64.

Remember that when changing the variable type, you may need to handle potential data loss or precision issues, especially when converting from a larger data type to a smaller one or when working with floating-point numbers. Always ensure that the conversion is safe and appropriate for your use case.

Conclusion

In conclusion, typecast in golang is a mechanism that allows you to convert values between different data types in a controlled and explicit manner. Here are some key takeaways:

  1. Static Typing: Go is a statically typed language, meaning that variable types are determined at compile-time and cannot change dynamically during program execution.
  2. Type Safety: Type casting helps ensure type safety in Go programs by requiring explicit conversions between incompatible types.
  3. Basic Type Conversion: Basic type conversion is achieved by explicitly casting values to the desired type. This is useful for converting between numeric types, such as int and float64.
  4. Type Assertion: Type assertion is used with interface values to determine and extract the underlying concrete value. It is particularly useful when working with interfaces and runtime polymorphism.
  5. Conversion Functions: Go provides packages like strconv for specific type conversion needs, such as converting strings to numbers.
  6. Custom Type Conversion: You can create custom types and define conversion methods to convert values between your custom types and built-in types.
  7. Data Loss Considerations: When performing type conversions, be mindful of potential data loss or precision issues, especially when dealing with different numeric types.
  8. Type Casting vs. Type Assertion: Type casting is used for type conversion, whereas type assertion is used for extracting values from interfaces.

Type cast in golang is a fundamental aspect of Go programming that helps you work with various data types and maintain type safety in your applications. Understanding how to use type casting effectively is essential for writing robust and reliable Go programs.