Go: More snippets – code examples
if / else if / else
package main
import "fmt"
func main() {
punkte := 73
if punkte >= 90 {
fmt.Println("excellent")
} else if punkte >= 70 {
fmt.Println("good")
} else {
fmt.Println("needs improvement")
}
}No parentheses around the condition, but always curly braces around the block. Go has no ternary operator.
for loop and range
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Runde", i)
}
for _, frucht := range []string{"Apple", "Pear"} {
fmt.Println(frucht)
}
}Go has only for: classic with a counter or with range over collections. The underscore discards the index you do not need.
Function with parameters
package main
import "fmt"
func begruesse(name, gruss string) string {
return gruss + ", " + name + "!"
}
func main() {
fmt.Println(begruesse("Ada", "Hello"))
fmt.Println(begruesse("Linus", "Hi"))
}Go has no default values for parameters. Alternatives: variadic parameters (...string), an options struct or several functions. name, gruss string shares the type.
Struct with methods and embedding
package main
import "fmt"
type Tier struct{ Name string }
func (t Tier) Sprich() string { return t.Name + " makes a sound" }
type Hund struct{ Tier }
func (h Hund) Sprich() string { return h.Name + " says Woof!" }
func main() {
fmt.Println(Hund{Tier{"Rex"}}.Sprich())
}Go has no classes: a struct holds the data, and methods attach via the receiver. Embedding (Tier in Hund) replaces inheritance – Hund gets the field Name and overrides Sprich.
Check errors and defer
package main
import (
"fmt"
"strconv"
)
func main() {
defer fmt.Println("Cleanup")
_, err := strconv.Atoi("abc")
if err != nil {
fmt.Println("Invalid:", err)
}
}Instead of try/catch, Go uses errors as return values (if err != nil). defer always runs when the function exits – the counterpart to finally.
Custom error type with errors.As
package main
import (
"errors"
"fmt"
)
type NichtGefunden struct{ ID int }
func (e *NichtGefunden) Error() string {
return fmt.Sprintf("id %d not found", e.ID)
}
func laden(id int) error {
return fmt.Errorf("laden: %w", &NichtGefunden{ID: id})
}
func main() {
err := laden(7)
fmt.Println(err) // load: id 7 not found
var nf *NichtGefunden
if errors.As(err, &nf) {
fmt.Println("ID:", nf.ID) // ID: 7
}
}%w wraps the error, errors.As searches the chain for the matching type and fills the target variable – this is how you handle specific errors selectively (e.g. 404 instead of 500).
Read and write a file
package main
import (
"fmt"
"os"
"strings"
)
func main() {
_ = os.WriteFile("notizen.txt", []byte("Line 1\nLine 2\n"), 0o644)
data, err := os.ReadFile("notizen.txt")
if err != nil {
panic(err)
}
fmt.Println(strings.TrimSpace(string(data)))
}os.WriteFile/os.ReadFile handle small files in one step (without open handles). For large files use os.Open + bufio.Scanner.
Read and write JSON
package main
import (
"encoding/json"
"fmt"
)
type Nutzer struct {
Name string `json:"name"`
Sprachen []string `json:"sprachen"`
}
func main() {
n := Nutzer{Name: "Ada", Sprachen: []string{"Python", "Go"}}
b, err := json.MarshalIndent(n, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(b))
var zurueck Nutzer
if err := json.Unmarshal(b, &zurueck); err != nil {
panic(err)
}
fmt.Println(zurueck.Sprachen[0]) // Python
}Struct tags (in backticks) define the JSON field names. Marshal produces JSON from Go values, Unmarshal fills a pointer to the target.
HTTP request (net/http)
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
func main() {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get("https://api.github.com/repos/golang/go")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
var repo struct {
Name string `json:"full_name"`
Stars int `json:"stargazers_count"`
}
if err := json.NewDecoder(resp.Body).Decode(&repo); err != nil {
log.Fatal(err)
}
fmt.Println(repo.Name, repo.Stars)
}Always set a timeout (the default client has none). Close the body with defer resp.Body.Close(). In real code, also check resp.StatusCode.
Minimal HTTP server
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/hallo", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello %s!", r.URL.Query().Get("name"))
})
log.Println("Server running on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}A server needs only the standard library. Call: http://localhost:8080/hallo?name=Ada. Since Go 1.22, routes support methods and placeholders, e.g. "GET /nutzer/{id}".
Generic functions Filter and Map
package main
import (
"fmt"
"strings"
)
func Filter[T any](s []T, ok func(T) bool) []T {
var res []T
for _, v := range s {
if ok(v) {
res = append(res, v)
}
}
return res
}
func Map[T, U any](s []T, f func(T) U) []U {
res := make([]U, 0, len(s))
for _, v := range s {
res = append(res, f(v))
}
return res
}
func main() {
gerade := Filter([]int{1, 2, 3, 4, 5, 6}, func(n int) bool { return n%2 == 0 })
fmt.Println(gerade) // [2 4 6]
fmt.Println(Map(gerade, func(n int) string { return strings.Repeat("*", n) })) // [** **** ******]
}Type parameters ([T any]) are usually inferred automatically at the call site. This gives you Filter/Map without list comprehensions – type-safe and without casts.
Command-line arguments (flag)
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
name := flag.String("name", "World", "Who to greet?")
laut := flag.Bool("laut", false, "in uppercase")
flag.Parse()
text := "Hello " + *name
if *laut {
text = strings.ToUpper(text)
}
fmt.Println(text)
}Call it e.g. with go run . -name Ada -laut; -h automatically generates help. The functions return pointers, hence *name. For larger CLIs there are libraries such as cobra.