bhylu.com

Advertisements

Go Exercises

Practise slices, map lookups and checked updates on a small original fixture.

How it works

Task: count the occupied slots, collect their IDs in their existing order, then decide whether two more parcels fit into a desk with five spaces. Zero marks an empty slot. Do not sort the IDs because the original slot order is part of this task. The worked answer keeps counting separate from the capacity decision.

Run this Go example

Install Go separately from the official Go downloads and check go version in a new terminal. The reviewed baseline is Go 1.27.3 on Windows amd64; the authored syntax and standard-library APIs require Go 1.22 or newer. Save the complete source below as exercises.go in a learning folder, then run go run exercises.go from that folder. These examples use only the standard library.

Bhylu has no Go browser runner. Apache, MySQL, PHP and the JavaScript or Python playground are not required to run these files. File examples own a temporary directory; HTTP client examples create an ephemeral loopback server and close it. They do not contact an external API.

Download the complete exercises.go · Download all source files with hash checks

For the optional collection download, save download-examples.mjs in a new learning folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/go/. The downloader refuses an existing bhylu-go-examples folder and installs or executes no Go code.

Example

exercises.go

package main

import (
	"fmt"
)

func main() {
	slots := []int{0, 23, 0, 21}
	ids := make([]int, 0)
	for _, id := range slots {
		if id != 0 {
			ids = append(ids, id)
		}
	}
	free := 5 - len(ids)
	fmt.Println(ids)
	fmt.Println("two fit", 2 <= free)
}

Expected result

[23 21]
two fit true

Two nonzero entries are appended in slot order. The desk has three remaining spaces, so a request for two fits. Extend the exercise by writing a helper that rejects a negative capacity and testing an empty slice and a full desk.

For language rules and APIs, use the Go language specification and standard-library documentation. The fictional examples are learning fixtures, not a deployed parcel service.

Advertisements