Library contents

Go Append to a map of slices

Collect parcels under their delivery route as each scan arrives.

A simple example

Append to a map of slices

  1. Start with A already holds [1]
  2. Do this Append 2 in the A group
  3. Result A holds [1, 2]
The map locates the group and its list stores both values.

Syntax

Go syntax
routes[key] = append(routes[key], parcel)
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Group two parcels on one delivery route

A small courier sorts parcels into a list for each route. The first North parcel needs a new list, while the next North parcel should join that same list without erasing the first one.

ResultP2, P8
main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    routes := make(map[string][]string)
    for _, parcel := range []string{"P2", "P8"} {
        routes["North"] = append(routes["North"], parcel)
    }
    fmt.Println(strings.Join(routes["North"], ", "))
}
Output
P2, P8

Both parcels join the North route in scan order.

Advertisements

Fill the east-studio tote

A courier sorts parcels into destination totes as the labels arrive. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?

GivenEast P4 · West P8 · East P2
Worked resultP4 · P2

Prepare a library transfer

Three crates arrive for different branches at the sorting desk. Append each parcel to the list for its destination. In what order do the parcels appear in the selected group?

GivenHill C8 · Park C2 · Hill C9
Worked resultC8 · C9

What to watch for

A missing key supplies a nil slice, which append accepts. The outer map must already be initialized.

Documentation for Append to a map of slices