Go maps.Clone
Keep yesterday’s price list available when the working menu changes.
A simple example
maps.Clone
- Start with A = 1
- Do this Copy the map, then set original A to 2
- Result Copy still has A = 1
Syntax
printed := maps.Clone(prices)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goKeep the price shown on yesterday's menu
A café changes its soup price after printing yesterday's menu. Accounts needs a snapshot of the earlier price to check old receipts even as the working price list changes.
package main
import (
"fmt"
"maps"
)
func main() {
prices := map[string]int{"Soup": 4}
printed := maps.Clone(prices)
prices["Soup"] = 5
fmt.Println(printed["Soup"])
}
4
The printed menu keeps the earlier soup price of four.
Save a café price list
A counter freezes the morning menu before an afternoon update. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?
Print a desk assignment
A secretary prints room assignments before moving the club. The desk takes a snapshot before changing the working record. What value is visible on the saved copy?
What to watch for
Assigning a map variable alone shares the same map. Clone creates a separate shallow copy.