Go examples

Practical, runnable Go snippets. Click any example to open it in the interactive Go playground, then edit the code and run it against a real Go toolchain.

package main

import "fmt"

func main() {
	fmt.Println("Hello from Go!")

	for i := 0; i < 10; i++ {
		fmt.Printf("fib(%d) = %d\n", i, fib(i))
	}
}

func fib(n int) int {
	if n < 2 {
		return n
	}
	return fib(n-1) + fib(n-2)
}

Run a Go program that prints Hello World and computes Fibonacci numbers.

Open in Go playground
package main

import (
	"fmt"
	"sort"
	"strings"
)

func main() {
	words := []string{"banana", "apple", "cherry", "apple", "banana", "apple"}

	// Count occurrences with a map.
	counts := map[string]int{}
	for _, w := range words {
		counts[w]++
	}

	// Sort the unique keys for stable output.
	keys := make([]string, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		fmt.Printf("%-8s %d\n", k, counts[k])
	}

	fmt.Println("joined:", strings.Join(keys, ", "))
}

Count word occurrences using slices, maps and sorting in Go.

Open in Go playground
package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	results := make([]int, 5)

	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func(n int) {
			defer wg.Done()
			results[n] = n * n
		}(i)
	}

	wg.Wait()
	fmt.Println("squares:", results)
}

Run concurrent work with goroutines and a sync.WaitGroup in Go.

Open in Go playground