Go Slice update with range
Trim every badge name while preserving registration order.
A simple example
Slice update with range
- Start with " A ", " B "
- Do this Trim each element
- Result "A", "B"
Syntax
names[i] = strings.TrimSpace(names[i])
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goClean the names on two visitor badges
A reception desk receives visitor names copied from an email. Extra spaces at the edges would make the printed badges look uneven, so the desk cleans each name while preserving arrival order.
package main
import (
"fmt"
"strings"
)
func main() {
names := []string{" Mira ", " Sam"}
for i := range names {
names[i] = strings.TrimSpace(names[i])
}
fmt.Println(strings.Join(names, ", "))
}
Mira, Sam
The cleaned names are ready for the badge printer.
Clean a volunteer roster
Two names pasted from a form have stray spaces. The printer trims surrounding spaces from each label. Which names remain on the badge sheet?
Prepare two exhibit labels
A curator copies padded names out of a spreadsheet. The printer trims surrounding spaces from each label. Which names remain on the badge sheet?
What to watch for
Assign through the index. Assigning only to a range value variable leaves the slice entry unchanged.