Go: Basics – code examples
Hello World
Use case: A first test of whether Go and the module work.
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}Every executable program needs package main and a main function; fmt.Println prints a line. Start it with go run ..
Variables and types
Use case: Store values and check their type.
package main
import "fmt"
func main() {
name := "Ada"
alter := 36
groesse := 1.68
aktiv := true
fmt.Println(name, alter, groesse, aktiv)
fmt.Printf("%T %T\n", alter, groesse)
}:= declares and initializes with type inference (output: Ada 36 1.68 true, then int float64). %T in Printf shows the type.
Date and time
Basics#time#format#duration
Use case: Calculate deadlines, format timestamps.
package main
import (
"fmt"
"time"
)
func main() {
jetzt := time.Date(2026, 3, 15, 9, 30, 0, 0, time.UTC)
fmt.Println(jetzt.Format("02.01.2006 15:04")) // 15.03.2026 09:30
fmt.Println(jetzt.AddDate(0, 0, 30).Format("02.01.2006")) // 14.04.2026
weihn := time.Date(2026, 12, 24, 0, 0, 0, 0, time.UTC)
fmt.Println(int(weihn.Sub(jetzt).Hours()/24), "days until Christmas") // 283
}Go does not format with codes like %Y but with the reference date "Mon Jan 2 15:04:05 2006" – 02.01.2006 stands for day.month.year. Sub returns a time.Duration.
Enum with iota and Stringer
Basics#iota#enum#stringer#const
Use case: Print fixed sets of choices (statuses, weekdays, roles) in a type-safe and readable way.
package main
import "fmt"
type Wochentag int
const (
Mo Wochentag = iota
Di
Mi
)
var namen = [...]string{"Mon", "Tue", "Wed"}
func (w Wochentag) String() string { return namen[w] }
func main() {
fmt.Println(Di, Mi) // Tue Wed
fmt.Printf("%d %v\n", Mi, Mi) // 2 Wed
}iota counts up from 0 in a const block. With the method String() (interface fmt.Stringer), fmt prints the name instead of the number. For many values there is the stringer tool.