Skip to content

Proposal: add a "merge" built-in function to join several slices. #23905

Closed
@dotaheor

Description

@dotaheor

The problem

Sometime, we need to insert a slice (call it x) into another (call it y) at the index i of y.
If the capacity of y is large enough to accept all elements of x, then things would simple.

func insert1(y, x []T, i int) []T {
	s := y[:len(s)+len(x)]
	copy(s[i+len(x):], s[i:])
	copy(s[i:], x)
	return s
}

However, the capacity of y is not large enough to accept all elements of x,
we must use make to allocate a new slice which is large enough to accept all elements of x and y.

func insert2(y, x []T, i int) []T {
	s := make([]T, 0, len(x)+len(y))
	s = append(s, y[:i]...)
	s = append(s, x...)
	s = append(s, y[i:]...)
	return s
}

The problem here is that the make function will clear all allocated bytes,
which is not essential for this case.

The proposal

So I propose a merge (or join, or concat) built-in function to merge several slices.

func merge(slices ...[][]T) []T

so that we can call

merge(y[:i], elements, y[i:])

which will be more efficient than the insert2 function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    LanguageChangeSuggested changes to the Go languageProposalv2An incompatible library change

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions