Skip to content
AgileLogics
5 min read

Type Conversion

Prerequisites: Constants & iota

Go never converts between types automatically — not even from int to float64. Every conversion is written out.

Syntax

f := float64(n)   // Type(value) converts between numeric types
i := int(f)       // truncates toward zero

Converting between numbers and text is different: it uses the strconv ("string conversion") package.

  • strconv.Itoa(n) — int to string ("integer to ASCII").
  • strconv.Atoi(s) — string to int. Because the text might not be a number, it returns two values: the number and an error (which is nil when everything worked).

Example

package main

import (
    "fmt"
    "strconv"
)

func main() {
    count := 7
    total := 2
    average := float64(count) / float64(total)
    fmt.Println(average)

    price := 19.99
    fmt.Println(int(price))

    label := "Item " + strconv.Itoa(42)
    fmt.Println(label)

    n, err := strconv.Atoi("123")
    fmt.Println(n+1, err)

    bad, err := strconv.Atoi("abc")
    fmt.Println(bad, err)
}

Expected output

3.5
19
Item 42
124 <nil>
0 strconv.Atoi: parsing "abc": invalid syntax

<nil> means "no error". You'll learn to check errors properly with if err != nil in the Multiple Return Values & Errors lesson.

Common mistakes

  • Writing count / total with two ints and expecting 3.5 — integer division gives 3. Convert before dividing.
  • Using string(65) to turn a number into text. That produces "A" (the character with code 65), not "65"; use strconv.Itoa instead. go vet warns about this mistake.
  • Ignoring the error from strconv.Atoi — on invalid input the number is silently 0.

Practice

Convert the string "25" to an int, add 5, and print the result along with the error value.

Show solution
package main

import (
    "fmt"
    "strconv"
)

func main() {
    n, err := strconv.Atoi("25")
    fmt.Println(n+5, err) // 30 <nil>
}