Go by Example

Values

Go's built-in scalar types - bool, integer variants, float32/float64, byte, rune, and string.

Go is statically typed: expression types are checked at compile time, and untyped constants get a type from context. The built-in scalar types cover booleans, integers of specific widths, floating-point numbers, and text.

Boolean values are true or false. Go has no truthiness - non-zero integers and non-nil pointers are not implicitly boolean.

package main
 
import "fmt"
 
func main() {
    fmt.Println(true && false) // false
    fmt.Println(true || false) // true
    fmt.Println(!true)         // false
}

Go has signed integers (int8, int16, int32, int64, and int), unsigned variants (uint8/byte, uint16, uint32, uint64, uint), and two floating-point types. int and uint are either 32 or 64 bits, depending on the target.

package main
 
import "fmt"
 
func main() {
    fmt.Println(1 + 2)           // 3       (int)
    fmt.Println(7.0 / 3.0)       // 2.3333… (float64)
    fmt.Println(7 / 3)           // 2       (integer division)
    fmt.Println(7 % 3)           // 1
 
    var b byte = 255             // alias for uint8
    fmt.Println(b)               // 255
}

Strings in Go are immutable sequences of bytes. They often contain UTF-8 text, but may contain arbitrary bytes. rune is an alias for int32 and represents a Unicode code point. byte is an alias for uint8 and represents a raw byte.

package main
 
import "fmt"
 
func main() {
    s := "Hello, δΈ–η•Œ"
 
    fmt.Println(len(s))           // 13 - byte count, not character count
    fmt.Println([]rune(s))        // slice of Unicode code points
 
    for i, r := range s {
        fmt.Printf("%d: %c\n", i, r)
    }
    // i is the byte offset; r is the rune at that offset
}

In production

range over a string yields runes (Unicode code points); len() returns bytes. Indexing uses byte offsets, so s[3] gives the fourth byte, not the fourth code point. Use range or []rune when processing code points. Rune counts are not counts of user-perceived characters; use Unicode grapheme segmentation for display or truncation that must preserve those characters.

Enjoyed this? Get more software craft delivered to your inbox.