Skip to content

Go Type Conversions

Go is statically typed and very strict. It never performs "implicit" conversions (e.g., adding an int to a float64 automatically). You must always be explicit.

1. Numeric Conversions

To convert between numbers, use the type name as a function.

package main

import "fmt"

func main() {
    var i int = 42
    var f float64 = float64(i) // int to float
    var u uint = uint(f)       // float to uint

    fmt.Println(i, f, u)
}

Warning: Converting a float64(3.9) to an int will result in 3 (truncation), not 4.

2. String Conversions (strconv)

Converting a number to a string (or vice versa) requires the strconv package.

import "strconv"

// 1. String to Int
i, _ := strconv.Atoi("123")

// 2. Int to String
s := strconv.Itoa(123)

// 3. String to Float
f, _ := strconv.ParseFloat("3.14", 64)

3. Type Assertions (Interfaces)

A type assertion provides access to an interface value's underlying concrete value.

var i interface{} = "hello"

// 1. Basic assertion (Dangerous: panics if not a string)
s := i.(string)

// 2. Safe assertion (Comma-ok idiom)
s, ok := i.(string)
if ok {
    fmt.Println(s)
} else {
    fmt.Println("Not a string!")
}

4. Type Switches

A type switch is a cleaner way to handle multiple possible types for an interface.

1
2
3
4
5
6
7
8
switch v := i.(type) {
case int:
    fmt.Println("It's an int:", v)
case string:
    fmt.Println("It's a string:", v)
default:
    fmt.Printf("Unknown type %T\n", v)
}

Why is Go so strict?

  1. Safety: Prevents hidden bugs where precision is lost or numbers overflow without you noticing.
  2. Clarity: By forcing you to write int64(x), the code clearly communicates that a conversion is happening.