Learn Go← Dashboard

Numbers, booleans, strings, bytes, runes, and type conversion.

Type Conversion

Go has no implicit numeric conversions. If you want to add an int and a float64, you must explicitly convert one of them. This trips up newcomers from JavaScript or Python, but it eliminates a whole class of subtle bugs.

The T(value) syntax

i := 42
f := float64(i)    // int → float64
u := uint(f)       // float64 → uint
s := string(65)    // ⚠️ int → string: gives "A", not "65"

float64 → int truncates toward zero — it does not round:

int(3.9)   // 3, not 4
int(-3.9)  // -3, not -4

Use math.Round, math.Floor, or math.Ceil if you want rounding.

go playground
Loading...

Strings ↔ numbers: use strconv

The string(65) trick above gives you the character "A", not the text "65". For real number-to-text conversion use the strconv package. (Modern go vet flags string(int) as a likely mistake.)

go playground
Loading...

| Conversion | Function | | -------------------- | --------------------------------------- | | int → string | strconv.Itoa(n) | | string → int | strconv.Atoi(s) (returns int, error) | | string → int64 | strconv.ParseInt(s, base, bits) | | string → float64 | strconv.ParseFloat(s, 64) | | bool → string | strconv.FormatBool(b) |

Bytes and runes are special

Because byte = uint8 and rune = int32, you can convert to and from them like any other integer:

b := byte('A')          // 65
r := rune(0x1F600)      // 😀
s := string([]rune{'h', 'é', 'l', 'l', 'o'})
What does `string(65)` evaluate to?