Go Tutorial · Go Basics · Lesson 5 of 30

Go Data Types

Integers, floats, strings, booleans, bytes, runes and type conversion.

Basic types

Type Examples
bool true, false
string "hello" (immutable UTF-8 bytes)
int, int8…int64, uint… 42, -7
float64, float32 3.14
byte (= uint8) a raw byte
rune (= int32) a Unicode code point: 'é'

Use int and float64 unless you have a reason not to.

Example 1
package main

import "fmt"

func main() {
	var age int = 36
	var height float64 = 1.68
	var initial rune = 'G'
	var b byte = 'A'
	fmt.Println(age, height, initial, string(initial), b)
	fmt.Printf("%T %T %T %T\n", age, height, initial, b)
	fmt.Println(7/2, 7.0/2, 7%2)
}

Output

36 1.68 71 G 65
int float64 int32 uint8
3 3.5 1

Run this on your computer — see “Get Started” for setup.

Conversion is explicit

Go never converts numeric types automatically — you must convert with T(value). Converting between strings and numbers uses the strconv package:

Example 2
package main

import (
	"fmt"
	"strconv"
)

func main() {
	a := 10
	b := 3.5
	total := float64(a) + b // must convert explicitly
	fmt.Println(total, int(b))

	n, err := strconv.Atoi("123")
	fmt.Println(n+1, err)
	_, err = strconv.Atoi("12abc")
	fmt.Println(err)
	s := strconv.Itoa(99) + " bottles"
	f, _ := strconv.ParseFloat("2.5", 64)
	fmt.Println(s, f*2)
}

Output

13.5 3
124 <nil>
strconv.Atoi: parsing "12abc": invalid syntax
99 bottles 5

Run this on your computer — see “Get Started” for setup.

Test yourself

Does Go automatically convert an int to a float64 in x + 1.5 where x is an int variable?

  1. Yes
  2. No — you must write float64(x)
Show answer

Answer: No — you must write float64(x)