Basic Types
Go is statically typed. Numeric types are explicit (no automatic conversion); strings are immutable byte sequences; nil is the zero value of pointers, slices, maps, channels, interfaces, and functions.
A tour of Go types
EXAMPLE
package main
import "fmt"
// Integers + floats — explicit sizes
var (
a int = -7
b int32 = 123
c uint64 = 1 << 40
d float64 = 3.14
)
// Strings are immutable; indexing returns a byte
func strBytes() {
s := "héllo"
fmt.Println(len(s)) // 6 — byte length, not rune count
fmt.Println([]byte(s)[0]) // 104
for i, r := range s { // ranges over runes
fmt.Printf("%d %c\n", i, r)
}
}
// Type conversions are explicit
func convert() {
i := 42
f := float64(i)
s := fmt.Sprintf("%d", i)
_ = f; _ = s
}
// Custom types — distinct, not aliases
type UserID int64
type Email string
func send(_ Email) {}
func main() {
var id UserID = 1
var e Email = "ada@example.com"
send(e)
// send("hi") // ERROR: untyped string isn't an Email at the call site (well, it is — but you get the idea once you wrap it in a struct)
_ = id
}
Why it matters
Distinct named types (type UserID int64) give you type safety on primitives — mixing up a UserID and an OrderID becomes a compile error.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…