Skip to content

Instantly share code, notes, and snippets.

@jpalala
Last active September 9, 2025 22:38
Show Gist options
  • Save jpalala/6b271a5b1498f6f6a320539aed18cb96 to your computer and use it in GitHub Desktop.
Save jpalala/6b271a5b1498f6f6a320539aed18cb96 to your computer and use it in GitHub Desktop.
Go zip
func Zip[T any](a, b []T) ([][2]T, error) {
    if len(a) != len(b) {
        return nil, fmt.Errorf("zip: lengths differ")
    }
    r := make([][2]T, len(a))
    for i, e := range a {
        r[i] = [2]T{e, b[i]}
    }
    return r, nil
}

Why zip?

1. Indexes and values

Keys and values before building a map

Imagine:

keys: ["id1", "id2", "id3"]

values: [100, 200, 300]

You can zip them first, then decide how to store them (like a map[string]int):

[{id1 100}, {id2 200}, {id3 300}]

2. Merging sensor or log data

  1. One system gives you timestamps.
  2. Another gives you readings.

You zip them to make a dataset of {time, reading} pairs. Without pairing, your time-series data becomes meaningless.

3. Sending related data together

When sending large datasets across the internet: If you just dump a flat list of numbers, the receiver won't know how they connect.

If you zip them (e.g., [latitude, longitude] pairs), the meaning is preserved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment