Cannot Convert Type

cannot convert x (variable of type string) to type int

Quick Answer

You cannot directly convert between incompatible types like string and int. Use strconv.Atoi or strconv.Itoa for string-number conversions.

Why This Happens

Go only allows type conversions between compatible types that share the same underlying representation. Converting a string to an int is not a simple type conversion because the memory layouts are different. You must use the strconv package for string-to-number conversions.

The Problem

func main() {
    s := "42"
    n := int(s) // cannot convert s (type string) to type int
    fmt.Println(n)
}

The Fix

func main() {
    s := "42"
    n, err := strconv.Atoi(s)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(n)
}

Step-by-Step Fix

  1. 1

    Identify the conversion

    Read the error to see which types are involved in the failed conversion.

  2. 2

    Find the correct function

    Use strconv.Atoi for string to int, strconv.Itoa for int to string, or fmt.Sprintf for general formatting.

  3. 3

    Handle errors

    Parsing functions return errors. Always check the error before using the converted value.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free