BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Keywords

Go 1.23

An overview of Go's 25 reserved keywords. This example demonstrates a program that utilizes a wide variety of these keywords in context, illustrating their roles in declarations, control flow, and type definitions.

Code

package main

import "fmt"

// 'type', 'struct', 'interface' are keywords for type definitions
type Runner interface {
    Run()
}

type Task struct {
    ID int
}

// 'func' declares functions/methods
func (t *Task) Run() {
    fmt.Printf("Task %d running\n", t.ID)
}

func main() {
    // 'var', 'map', 'make' (built-in, not keyword, but related)
    var tasks = make(map[int]Runner)

    // 'for', 'range' for iteration
    for i := 0; i < 3; i++ {
        tasks[i] = &Task{ID: i}
    }

    // 'switch', 'case', 'default' for branching
    state := "start"
    switch state {
    case "start":
        // 'go' starts a goroutine
        go func() {
            fmt.Println("Started!")
        }()
    default:
        fmt.Println("Unknown state")
    }

    // 'select', 'case' for channel operations
    ch := make(chan int)
    // 'defer' schedules execution until return
    defer close(ch)

    go func() {
        ch <- 1
    }()

    select {
    case val := <-ch:
        // 'if', 'else'
        if val > 0 {
            fmt.Println("Received positive:", val)
        } else {
            fmt.Println("Received non-positive")
        }
    }
    
    // 'return' exits the function
    return
}

Explanation

Go has a concise set of only 25 reserved keywords, which is significantly fewer than many other languages like C++ or Java. These keywords are reserved tokens that cannot be used as identifiers (like variable or function names). This minimalism contributes to Go's readability and fast compilation times, as the parser has fewer special cases to handle.

The keywords can be broadly categorized into declarations (var, const, type, func, package, import), composite types (map, struct, interface, chan), control flow (if, else, for, range, break, continue, switch, select, case, default, fallthrough, return, goto), and specific Go features (go, defer). Understanding these is fundamental to reading and writing any Go code.

In this example, we construct a program that artificially combines many of these keywords to show them in context. We define types with struct and interface, manage control flow with switch and select, and handle concurrency with go and chan. Note that some familiar words like int, true, or make are predeclared identifiers, not keywords, meaning they can technically be shadowed (though you shouldn't).

  • Declarations: package, import, func, type, var, const
  • Control Structures: if, else, for, switch, case, default, break, continue, fallthrough, goto, return
  • Concurrency: go, select, chan
  • Types & Scope: struct, interface, map, range, defer

Code Breakdown

6-8
Using 'type' and 'interface' to define a new interface named Runner. These are declaration keywords that define the shape of data and behavior.
30-38
The 'switch', 'case', and 'default' keywords form a conditional branch. Inside the case, the 'go' keyword spawns a new goroutine, a lightweight thread managed by the Go runtime.
43
The 'defer' keyword pushes a function call onto a stack. This call (close(ch)) is executed immediately before the surrounding function (main) returns, ensuring cleanup happens even if errors occur.
49-57
The 'select' keyword is like a switch statement but for channels. It waits until one of its cases can proceed. Here, it waits to receive a value from 'ch'.