Last modified: Jan 22, 2026 By Alexander Williams

Go Type Conversion: Safe Variable Changes

Type conversion is a core task in Go programming. You often need to change a variable from one type to another. Doing this safely prevents runtime errors.

Go is a statically typed language. This means variable types are checked at compile time. You cannot mix types freely. You must convert them explicitly.

This guide covers safe methods for type conversion. We will look at basic conversion, string conversion, and interface assertion.

Understanding Go's Type System

Go has a strong type system. Each variable has a fixed type. You cannot assign a value of one type to a variable of another type without conversion.

This prevents many common bugs. It makes your code more predictable. But it requires you to handle conversions carefully.

For example, you cannot add an integer to a float directly. You must convert one type to match the other first. Understanding Go default values for uninitialized variables is also key to safe code.

Basic Type Conversion (Type Casting)

The simplest method is direct type conversion. Use the syntax T(v). Here, T is the target type and v is the value.

This works for compatible numeric types. You can convert between int, float, and similar types.


package main

import "fmt"

func main() {
    var myInt int = 42
    var myFloat float64 = float64(myInt) // Convert int to float64
    var newInt int = int(myFloat)        // Convert float64 back to int

    fmt.Println("Original int:", myInt)
    fmt.Println("Converted float64:", myFloat)
    fmt.Println("Converted back int:", newInt)

    // Converting between int sizes
    var bigInt int64 = 500
    var smallInt int32 = int32(bigInt)
    fmt.Println("int64 to int32:", smallInt)
}

Original int: 42
Converted float64: 42
Converted back int: 42
int64 to int32: 500

Important: Converting a float to an integer truncates the decimal part. It does not round. Data loss can occur.

Also, converting a large int64 to a small int32 can cause overflow. The value wraps around. This leads to incorrect data.

Converting to and from Strings

String conversion is very common. Use the strconv package. It provides safe functions for parsing and formatting.

Do not use simple type conversion for strings and numbers. It will not work. You must use strconv.


package main

import (
    "fmt"
    "strconv"
)

func main() {
    // Integer to String
    num := 123
    str := strconv.Itoa(num) // Itoa = Integer to ASCII
    fmt.Println("String:", str, "Length:", len(str))

    // String to Integer
    input := "456"
    parsedNum, err := strconv.Atoi(input) // Atoi = ASCII to Integer
    if err != nil {
        fmt.Println("Conversion error:", err)
    } else {
        fmt.Println("Parsed integer:", parsedNum)
    }

    // String to Float
    floatStr := "78.9"
    parsedFloat, err := strconv.ParseFloat(floatStr, 64)
    if err != nil {
        fmt.Println("Float conversion error:", err)
    } else {
        fmt.Println("Parsed float:", parsedFloat)
    }

    // Float to String with formatting
    myFloat := 3.14159
    floatToStr := strconv.FormatFloat(myFloat, 'f', 2, 64) // 'f' format, 2 decimal places
    fmt.Println("Formatted string:", floatToStr)
}

String: 123 Length: 3
Parsed integer: 456
Parsed float: 78.9
Formatted string: 3.14

Always check the error return value from functions like strconv.Atoi. This prevents crashes from bad input. For more on handling text, see our guide on Go list of strings.

Type Assertion for Interfaces

Interfaces can hold values of any type. To get the underlying value, use a type assertion. The syntax is value, ok := interfaceVar.(Type).

The ok boolean tells you if the assertion succeeded. Always use this safe two-value form.


package main

import "fmt"

func main() {
    var myInterface interface{}

    myInterface = "Hello, Go"
    // Safe type assertion
    strVal, ok := myInterface.(string)
    if ok {
        fmt.Println("It's a string:", strVal)
    } else {
        fmt.Println("Not a string!")
    }

    myInterface = 100
    intVal, ok := myInterface.(int)
    if ok {
        fmt.Println("It's an int:", intVal)
    } else {
        fmt.Println("Not an int!")
    }

    // This will fail safely
    failedVal, ok := myInterface.(float64)
    if !ok {
        fmt.Println("Correctly failed to assert as float64")
        // failedVal will be the zero value for float64 (0.0)
        fmt.Println("Value of failedVal:", failedVal)
    }
}

It's a string: Hello, Go
It's an int: 100
Correctly failed to assert as float64
Value of failedVal: 0

Never use the single-value form like val := interfaceVar.(Type). It will panic if the assertion fails. The two-value form is the safe way.

Best Practices for Safe Conversion

Follow these rules to avoid errors.

First, always check for errors. Functions in strconv return an error. Ignoring it is risky.

Second, handle potential data loss. Converting a float to an int loses precision. Converting a large int to a small int may overflow.

Third, use the safe two-value type assertion. It prevents runtime panics.

Fourth, write clear code. If you are doing complex conversions, add comments. Use helper functions. For example, you might declare multiple variables in one line during conversion steps to keep logic tight.

Finally, test your conversions. Use different input values. Include edge cases like negative numbers, zero, and large values.

Common Pitfalls and How to Avoid Them

New Go developers make some common mistakes.

One pitfall is assuming conversion rounds floats. It truncates. Use math.Round before conversion if you need rounding.

Another is forgetting that string(int) converts to a character, not a number. Use strconv.Itoa instead.

Also, converting between incompatible types causes a compile error. You cannot convert a struct to an int directly. You must extract the relevant field first.

Using type assertion on a non-interface value is an error. Type assertion only works on interface types.

Conclusion

Safe type conversion is essential in Go. Use direct conversion for compatible numeric types. Use the strconv package for strings. Use the two-value form for type assertions.

Always check errors. Be aware of data loss. Write clear and tested code.

Mastering these techniques makes your Go programs robust. They will handle data correctly and avoid runtime crashes. For more on working with variables, learn how to print variable values in Go to debug your conversions.

Start practicing with simple conversions. Then move to more complex scenarios. Your code will become safer and more reliable.