Zip Two Slices Into Aligned Pairs
Align two parallel slices into paired records by index and stop at the shorter side, so leftover names never get fabricated scores.
Code
package main
import "fmt"
// Pair 是对齐产物:每个下标各取一侧组成一条记录
type Pair struct {
Name string
Score int
}
// zip joins two slices into aligned pairs,以较短一侧为准
func zip(names []string, scores []int) []Pair {
n := min(len(names), len(scores))
pairs := make([]Pair, 0, n)
for i := 0; i < n; i++ {
pairs = append(pairs, Pair{Name: names[i], Score: scores[i]})
}
return pairs
}
func main() {
names := []string{"ana", "bob", "cid", "dee"}
scores := []int{91, 84} // 短一侧:多余的 cid、dee 不参与配对
for _, p := range zip(names, scores) {
fmt.Printf("aligned: %s=%d\n", p.Name, p.Score)
}
}What the source does next
Zip Two Slices Into Aligned Pairs keeps everything in the functions zip and main.
The loop for i := 0; i < n; i++ is the only repeated construct.
Applying it
Entry signature: func zip(names []string, scores []int) []Pair
Output lines are prefixed (aligned:), which lets you match every output line to its step.
Running the file executes main, which drives zip in order.
Statements that matter
pairs = append(pairs, Pair{Name: names[i], Score: scores[i]})
for _, p := range zip(names, scores) {
fmt.Printf("aligned: %s=%d\n", p.Name, p.Score)
}
pairs := make([]Pair, 0, n)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Zip Two Slices Into Aligned Pairs print when run?
- No setup needed: run the file and look for labeled lines like `aligned:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.