Review generated event collector

from Slices
Go 1.27 advanced 6 min 3 issues to find

Review this generated event collector against the stated task.

Collect at most limit events in channel order, return payloads that no longer alias producer buffers, and handle invalid limits without panicking.

Go
package events

import "sort"

type Event struct {
    ID      int
    Payload []byte
}

func collect(ch <-chan Event, limit int) []Event {
    events := make([]Event, limit)
    for event := range ch {
        events = append(events, event)
        if len(events) == limit {
            break
        }
    }
    sort.Slice(events, func(i, j int) bool {
        return events[i].ID < events[j].ID
    })
    return events
}

generated code is illustrative, not from any one model

Open in playground
Report an error