This checkpoint combines the day's three ideas in one small type: when slices share storage, when append writes into someone else's array, and how to hand out a copy. Nothing in it is a repeat of an exercise: you decide where sharing could leak and close each leak.
A Log keeps entries in the order they arrived. Its method Recent(n int) []string returns the last n entries, or all of them when there are fewer than n. A caller may change the result, or append to it, without the log noticing.
Before you start
- Which expression gives the last
nelements of a slice, and does it share storage with the log? - If a caller appends to that subslice, where does the new element go?
- What should
Recent(10)return for a log of four entries?
Your turn
The starter has Log and a main that tries to damage it through the result of Recent. Write Recent. When it is safe, the program prints:
recent: [Edited d Extra]
all: [a b c d]
log: [a b c d]package main
import (
"fmt"
)
type Log struct {
entries []string
}
func (l *Log) Recent(n int) []string {
return nil
}
func main() {
log := Log{entries: make([]string, 0, 8)}
log.entries = append(log.entries, "a", "b", "c", "d")
recent := log.Recent(2)
if len(recent) > 0 {
recent[0] = "Edited"
}
recent = append(recent, "Extra")
fmt.Println("recent:", recent)
fmt.Println("all: ", log.Recent(10))
fmt.Println("log: ", log.entries)
}Hint 1: the idea
l.entries[len(l.entries)-n:] gives the right elements, but it shares the log's array, and the log has spare capacity after its last entry. An independent copy closes both leaks at once.
Hint 2: a first step
First return the subslice directly, with n limited by min(n, len(l.entries)). Run it: the log shows Edited and its array has taken Extra in its spare room. Then change only the return line.
Worked solution
package main
import (
"fmt"
"slices"
)
type Log struct {
entries []string
}
func (l *Log) Recent(n int) []string {
n = min(n, len(l.entries))
return slices.Clone(l.entries[len(l.entries)-n:])
}
func main() {
log := Log{entries: make([]string, 0, 8)}
log.entries = append(log.entries, "a", "b", "c", "d")
recent := log.Recent(2)
if len(recent) > 0 {
recent[0] = "Edited"
}
recent = append(recent, "Extra")
fmt.Println("recent:", recent)
fmt.Println("all: ", log.Recent(10))
fmt.Println("log: ", log.entries)
}recent: [Edited d Extra]
all: [a b c d]
log: [a b c d]Returning the subslice directly prints log: [a b Edited d], and the hidden fifth box of the log's array now holds Extra, ready to surprise the next append to the log. slices.Clone gives the caller an array of its own, so neither the edit nor the append can reach the log. min keeps Recent(10) from slicing before index 0.
Completion is saved in this browser only. It does not measure mastery.