Skip to content

proposal: slices: add CollectN with preallocated size. #68261

@earthboundkid

Description

@earthboundkid

Proposal Details

As discussed in #61900, it's a shame that slices.Collect(maps.Keys(m)) and slices.Sorted(maps.Keys(m)) don't preallocate the size of m. You can work around it by writing slices.Sorted(slices.Append(make([]T, 0, len(m)), maps.Keys(m))), but that's kind of ugly.

I propose adding func CollectN[S ~[]T, T any](seq iter.Seq[T], minsize int) S to slices that just returns Append(make([]T, 0, minsize), seq). It would help with map keys but also other container types where you know the length in advance or can at least make a good guess.

Sorting map keys more efficiently would look like keys := slices.CollectN(maps.Keys(m), len(m); slices.Sort(keys).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions