code-playpad

Experimental Go, with the official Go 1.27.3 compiler

language="go" (or golang) compiles a Go program with the official Go 1.27.3 compiler and linker, built for WebAssembly from the Go release with no changes, and runs it in a Web Worker. Programs use 32 standard-library packages. The first Run downloads about 21 MB from jsDelivr; later runs use Cache Storage.

An independent project, not affiliated with or endorsed by Google or the Go project.

Hello

package main import "fmt" func main() { names := []string{"Ada", "Grace", "Ken"} for i, name := range names { fmt.Printf("%d: Hello, %s!\n", i+1, name) } }

Reading stdin

Input is prefilled: edit the stdin box before pressing Run.

package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { var used []string sum := 0 for _, field := range strings.Fields(scanner.Text()) { n, err := strconv.Atoi(field) if err != nil { fmt.Printf("skipped %q: not a number\n", field) continue } used = append(used, field) sum += n } fmt.Printf("%s = %d\n", strings.Join(used, " + "), sum) } } 3 4 10 20 30

Two sum with a map

package main import "fmt" // twoSum returns the indexes of the two numbers that add up to target. func twoSum(nums []int, target int) (int, int, bool) { seen := map[int]int{} // value -> index for i, n := range nums { if j, ok := seen[target-n]; ok { return j, i, true } seen[n] = i } return 0, 0, false } func main() { fmt.Println(twoSum([]int{2, 7, 11, 15}, 9)) fmt.Println(twoSum([]int{3, 2, 4}, 6)) fmt.Println(twoSum([]int{1, 2}, 7)) }

Slices

A slice is a window onto an array: slicing shares memory, append grows it, and the slices package sorts and searches.

package main import ( "fmt" "slices" ) // maxSubArray is Kadane's algorithm: the largest sum of a contiguous run. func maxSubArray(nums []int) int { best, current := nums[0], nums[0] for _, n := range nums[1:] { current = max(n, current+n) best = max(best, current) } return best } func main() { nums := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} fmt.Println("nums:", nums, "len", len(nums)) fmt.Println("max subarray sum:", maxSubArray(nums)) window := nums[3:7] // shares memory with nums window[0] = 40 fmt.Println("window:", window, "nums[3]:", nums[3]) sorted := slices.Clone(nums) slices.Sort(sorted) fmt.Println("sorted copy:", sorted) fmt.Println("min, max:", slices.Min(nums), slices.Max(nums)) i, found := slices.BinarySearch(sorted, 2) fmt.Println("2 in sorted at", i, found) var squares []int for n := range 6 { squares = append(squares, n*n) } slices.Reverse(squares) fmt.Println("squares, reversed:", squares) }

Structs, methods and interfaces

package main import ( "fmt" "math" ) type Shape interface { Area() float64 Perimeter() float64 } type Rect struct{ W, H float64 } type Circle struct{ R float64 } func (r Rect) Area() float64 { return r.W * r.H } func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) } func (c Circle) Area() float64 { return math.Pi * c.R * c.R } func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R } // String makes fmt print a Rect or Circle this way. func (r Rect) String() string { return fmt.Sprintf("rect %gx%g", r.W, r.H) } func (c Circle) String() string { return fmt.Sprintf("circle r=%g", c.R) } // Scale has a pointer receiver, so it changes the Rect it is called on. func (r *Rect) Scale(k float64) { r.W *= k; r.H *= k } func main() { r := Rect{W: 3, H: 4} r.Scale(2) shapes := []Shape{r, Circle{R: 1.5}} total := 0.0 for _, s := range shapes { fmt.Printf("%-12v area %6.2f perimeter %6.2f\n", s, s.Area(), s.Perimeter()) total += s.Area() } fmt.Printf("total area: %.2f\n", total) if c, ok := shapes[1].(Circle); ok { fmt.Println("the second shape is a circle of radius", c.R) } }

Sorting

package main import ( "cmp" "fmt" "slices" "sort" ) // merge combines overlapping intervals, after sorting them by start. func merge(intervals [][2]int) [][2]int { slices.SortFunc(intervals, func(a, b [2]int) int { return cmp.Compare(a[0], b[0]) }) var out [][2]int for _, iv := range intervals { if n := len(out); n > 0 && iv[0] <= out[n-1][1] { out[n-1][1] = max(out[n-1][1], iv[1]) } else { out = append(out, iv) } } return out } type Player struct { Name string Score int } func main() { fmt.Println(merge([][2]int{{8, 10}, {1, 3}, {2, 6}, {15, 18}, {17, 20}})) players := []Player{{"Ada", 90}, {"Linus", 75}, {"Grace", 90}, {"Ken", 82}} // Highest score first; ties by name. slices.SortFunc(players, func(a, b Player) int { return cmp.Or(cmp.Compare(b.Score, a.Score), cmp.Compare(a.Name, b.Name)) }) for rank, p := range players { fmt.Printf("%d. %-6s %d\n", rank+1, p.Name, p.Score) } words := []string{"banana", "kiwi", "apple", "fig"} sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) }) fmt.Println("by length:", words) }

Strings and runes

package main import ( "fmt" "slices" "strings" "unicode" "unicode/utf8" ) func isPalindrome(s string) bool { var letters []rune for _, r := range strings.ToLower(s) { if unicode.IsLetter(r) || unicode.IsDigit(r) { letters = append(letters, r) } } for i, j := 0, len(letters)-1; i < j; i, j = i+1, j-1 { if letters[i] != letters[j] { return false } } return true } // groupAnagrams puts words with the same letters together. func groupAnagrams(words []string) [][]string { groups := map[string][]string{} var order []string for _, w := range words { key := []rune(w) slices.Sort(key) k := string(key) if _, ok := groups[k]; !ok { order = append(order, k) } groups[k] = append(groups[k], w) } var out [][]string for _, k := range order { out = append(out, groups[k]) } return out } func main() { for _, s := range []string{"A man, a plan, a canal: Panama", "Gopher"} { fmt.Printf("%q palindrome? %v\n", s, isPalindrome(s)) } fmt.Println(groupAnagrams([]string{"eat", "tea", "tan", "ate", "nat", "bat"})) // Capitalize each word. word[:1] would be one byte, half of "ü", so decode a rune. var b strings.Builder for i, word := range strings.Fields("über quick brown fox") { if i > 0 { b.WriteString("-") } r, size := utf8.DecodeRuneInString(word) b.WriteRune(unicode.ToUpper(r)) b.WriteString(word[size:]) } fmt.Println(b.String()) word := "héllo, 世界" fmt.Println(len(word), "bytes,", len([]rune(word)), "runes") }

A heap with container/heap

package main import ( "container/heap" "fmt" ) // A min-heap of ints, built on container/heap. type MinHeap []int func (h MinHeap) Len() int { return len(h) } func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] } func (h MinHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *MinHeap) Push(x any) { *h = append(*h, x.(int)) } func (h *MinHeap) Pop() any { old := *h n := len(old) x := old[n-1] *h = old[:n-1] return x } // kthLargest keeps the k largest numbers seen so far; the smallest of them is on top. func kthLargest(nums []int, k int) int { h := &MinHeap{} for _, n := range nums { heap.Push(h, n) if h.Len() > k { heap.Pop(h) } } return (*h)[0] } func main() { nums := []int{3, 2, 1, 5, 6, 4} for k := 1; k <= 3; k++ { fmt.Printf("k=%d: %d\n", k, kthLargest(nums, k)) } }

Errors

Functions return an error as their last result; %w wraps one, and errors.Is finds it again.

package main import ( "errors" "fmt" "strconv" ) var ErrTooOld = errors.New("too old") func parseAge(s string) (int, error) { age, err := strconv.Atoi(s) if err != nil { return 0, fmt.Errorf("parse %q: %w", s, err) } if age > 150 { return 0, fmt.Errorf("age %d: %w", age, ErrTooOld) } return age, nil } func main() { for _, input := range []string{"42", "abc", "200"} { age, err := parseAge(input) switch { case errors.Is(err, ErrTooOld): fmt.Println("rejected:", err) case err != nil: fmt.Println("error:", err) default: fmt.Println("age", age) } } }

Several files

Every .go file in the top folder is part of package main.

package main import "fmt" // isValid checks that every bracket is closed in the right order. func isValid(s string) bool { pairs := map[rune]rune{')': '(', ']': '[', '}': '{'} var stack Stack[rune] for _, r := range s { if open, ok := pairs[r]; ok { if top, ok := stack.Pop(); !ok || top != open { return false } } else { stack.Push(r) } } return stack.Len() == 0 } func main() { for _, s := range []string{"()[]{}", "([)]", "{[]}", "(("} { fmt.Printf("%-8s %v\n", s, isValid(s)) } } package main // Stack is a generic last-in, first-out stack. type Stack[T any] struct{ items []T } func (s *Stack[T]) Push(x T) { s.items = append(s.items, x) } func (s *Stack[T]) Len() int { return len(s.items) } func (s *Stack[T]) Pop() (T, bool) { var zero T if len(s.items) == 0 { return zero, false } x := s.items[len(s.items)-1] s.items = s.items[:len(s.items)-1] return x, true }

A compiler error

package main import "fmt" func main() { var answer int = "forty-two" fmt.Println(answer) }

A panic

package main import "fmt" func main() { nums := []int{1, 2, 3} i := len(nums) fmt.Println(nums[i]) }

Stop a runaway loop

package main import "fmt" func main() { fmt.Println("Press Stop.") for { } }

Limits