Beginner Fundamentals

Data Types

Go is statically typed, so every value has a type known at compile time. Knowing the basic types is essential.

Common types

  • int for whole numbers (e.g. 42)
  • float64 for decimal numbers (e.g. 3.14)
  • string for text (e.g. "hello")
  • bool for true or false
var quantity int = 5
var weight float64 = 2.5
var label string = "box"
var shipped bool = true

Checking a type

The %T verb prints the type of a value.

x := 10
fmt.Printf("%T\n", x) // int

Explicit conversion

Go never converts numeric types automatically. You must convert explicitly using T(value).

var i int = 7
var f float64 = float64(i)  // int to float64
var u int = int(f)          // float64 to int

fmt.Println(f, u)

Mixing types without conversion is an error:

// var sum = i + f // compile error: mismatched types
sum := float64(i) + f // correct
fmt.Println(sum)