Start learning free

LESSON 14 OF 338 · VARIABLES

Type Conversion in Go: strconv and Casts

Lesson Read the full explanation

Every value in Go has a type. Sometimes we need to convert a value from one type to another.

Common conversions in this lesson:

strconv.Itoa(x)      // converts an int to a string
int(x)               // converts a float64 to an int, dropping decimals
strconv.Atoi(s)      // converts a string to an int

Examples:

age := 25
ageStr := strconv.Itoa(age)  // "25"

price := 9.99
priceInt := int(price)       // 9

year := "2024"
yearInt, _ := strconv.Atoi(year) // 2024

Note that converting a float to an int drops the decimal part. It does not round.

Assignment
Follow the Coding Tutorial and convert each variable to a different type.


Hint
Use strconv.Itoa, int(...), and strconv.Atoi.

STEP 1 OF 3
    Ctrl + Enter to check

    GO · VARIABLES

    Type Conversion in Go, explained

    What type conversion is

    Every variable in Go has one type, fixed when the program compiles. An int stays an int, a float64 stays a float64 and a string stays a string. Type conversion creates a new value of a different type from an existing one.

    Go never converts types for you behind the scenes. If you multiply a float64 by an int, the program does not compile:

    count := 4
    price := 2.5
    // total := price * count  // error: mismatched types float64 and int
    total := price * float64(count)
    fmt.Println(total) // 10
    

    That strictness is deliberate: every conversion is visible in the code, so you always know where a value changes type and where it might lose information. You need conversions whenever data arrives in one form and you use it in another: a number read as text that you want to add to, an integer you want to put into a message, or a decimal you need as a whole number.

    Syntax and examples

    Between number types: T(x)

    To convert between numeric types, write the target type as if it were a function: float64(x), int(x), int64(x). Going from int to float64 is straightforward. Going from float64 to int drops everything after the decimal point. It does not round; it truncates toward zero:

    price := 9.99
    fmt.Println(int(price)) // 9
    
    loss := -9.99
    fmt.Println(int(loss)) // -9, not -10
    
    // Round first if that is what you want (import "math"):
    fmt.Println(int(math.Round(price))) // 10
    

    Between numbers and text: the strconv package

    A string like "2024" is a sequence of characters, not a number, so int(...) can't turn it into one. Conversions between text and numbers live in the standard strconv package, which you import with import "strconv":

    • strconv.Itoa(x) turns an int into its decimal text, so strconv.Itoa(25) is "25". The name is short for "integer to ASCII".
    • strconv.Atoi(s) goes the other way and returns two values: the number and an error. The error is nil when the text is a valid integer.
    age := 25
    ageStr := strconv.Itoa(age)
    fmt.Println(ageStr + " years") // 25 years
    
    n, err := strconv.Atoi("12a")
    if err != nil {
        fmt.Println(err) // strconv.Atoi: parsing "12a": invalid syntax
    }
    fmt.Println(n) // 0
    

    Checking err is the normal Go pattern. When parsing fails, Atoi returns 0, and without the check you couldn't tell a failed parse from the text "0".

    A quick reference

    FromToHowExample result
    intstringstrconv.Itoa(x)"25"
    stringintstrconv.Atoi(s)2024 and an error
    float64intint(x)9 from 9.99
    intfloat64float64(x)25 as a float
    stringfloat64strconv.ParseFloat(s, 64)9.99 and an error

    Common mistakes and gotchas

    • string(n) is not strconv.Itoa(n). Converting an integer with string(...) treats it as a Unicode code point, so 65 becomes "A", not "65". go vet warns about this conversion; use strconv.Itoa for digits.
    • Expecting rounding. A variable holding 2.99 converts to 2 with int(...). Truncation toward zero also means negative values move up: -2.99 becomes -2.
    • Converting a constant that doesn't fit. int(price) works on a variable, but int(9.99) written with a literal does not compile: a constant converted to an integer type must be a whole number that fits in it.
    • Using int(...) on text. int("5") is a compile error; strings need strconv.
    • Ignoring the error. Atoi rejects anything that isn't a plain integer, including surrounding spaces: " 42" fails. Discarding the error with _ is only safe when you know the text is valid.
    • Narrowing integers. Converting a variable to a smaller integer type keeps only the low bits, silently: an int holding 300 converted with int8(...) becomes 44.
    • Unused names. Go refuses to compile a program with a local variable or an import that is never used. That's one reason the blank identifier _ exists: it accepts a value you don't need, like the error from Atoi.

    The exercise, step by step

    The lesson starts with three variables of three different types: age is an int, price is a float64 and year is a string. Your job is to create a converted copy of each.

    1. Integer to text. Declare ageStr with := and give it strconv.Itoa(age). It holds the string "25".
    2. Decimal to integer. Declare priceInt as int(price). The decimals are dropped, so it holds 9.
    3. Text to integer. strconv.Atoi(year) returns two values, so the declaration needs two names on the left. Keep the number in yearInt and discard the error with _, which is safe because "2024" is a valid integer. yearInt holds 2024.
    age := 25
    price := 9.99
    year := "2024"
    
    ageStr := strconv.Itoa(age)
    priceInt := int(price)
    yearInt, _ := strconv.Atoi(year)
    

    After these lines, ageStr + "!" is valid string concatenation and yearInt + 1 is ordinary arithmetic giving 2025. Neither would compile with the original variables.

    Key takeaways

    • Go never converts types implicitly; you write every conversion yourself.
    • Numeric conversions use the type name: int(x), float64(x).
    • int(...) on a float64 truncates toward zero; use math.Round first to round.
    • Text and numbers convert through strconv: Itoa for int to string, Atoi for string to int.
    • Atoi returns a value and an error; check the error unless you are sure the text is valid.
    • string(65) is "A", not "65".
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free