Go by Example: Keywords
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

