Skip to content

Go Type Casting

In Go, converting a value from one type to another is called type conversion. Unlike some languages that allow implicit conversions between certain types (like int to float), Go requires conversions to be explicit.

This means you must explicitly state the type you want to convert to. This design choice enhances code clarity and prevents potential bugs arising from unexpected automatic conversions.

The syntax for type conversion is straightforward:

TargetType(expression)

Where TargetType is the type you want to convert to, and expression is the value or variable you are converting.

  1. Numeric Conversions: Converting between different integer types or between integer and floating-point types.
var i int = 42
var f float64 = float64(i) // Convert int to float64
var u uint = uint(i) // Convert int to uint
var fLarge float64 = 12345.678
var iTruncated int = int(fLarge) // Convert float64 to int (fractional part discarded)
fmt.Println(i, f, u) // Output: 42 42 42
fmt.Println(fLarge, iTruncated) // Output: 12345.678 12345

Caution: Converting from a larger type to a smaller type (e.g., int64 to int32) or from float to integer can result in truncation or loss of data if the value is outside the range of the target type.

  1. Integer Division: Performing floating-point division with integers.

If you divide two integers, Go performs integer division, discarding the remainder.

sum := 17
count := 5
resultInt := sum / count // Integer division: resultInt is 3

To get a floating-point result, convert one or both operands to a floating-point type before the division:

package main
import "fmt"
func main() {
var sum int = 17
var count int = 5
var mean float64
// Convert integers to float64 before division
mean = float64(sum) / float64(count)
fmt.Printf("Value of mean: %f\n", mean)
}

Output:

Value of mean: 3.400000
  1. Conversions involving byte and rune: Converting between integers, byte (uint8), and rune (int32).
var char byte = 'A' // byte is alias for uint8
var code int = int(char)
fmt.Printf("Character: %c, Code: %d\n", char, code) // Output: Character: A, Code: 65
var r rune = '世' // rune is alias for int32
var rCode int = int(r)
fmt.Printf("Rune: %c, Code: %d\n", r, rCode) // Output: Rune: 世, Code: 19990

You cannot directly convert between incompatible types, such as int and string, or bool and int, using this basic conversion syntax. For those scenarios, you typically use functions from standard library packages like strconv (for string conversions).

var num int = 100
// var str string = string(num) // Compile-time error: cannot convert num (type int) to type string
// Correct way using strconv package:
import "strconv"
var str string = strconv.Itoa(num) // Itoa: Integer to ASCII (string)
fmt.Println(str) // Output: "100"

Type conversion is a fundamental operation in Go for managing data across different representations while maintaining type safety.