Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: golang.org/x/exp/slices: Add "Merge" #61815

Closed
6543 opened this issue Aug 7, 2023 · 3 comments
Closed

proposal: golang.org/x/exp/slices: Add "Merge" #61815

6543 opened this issue Aug 7, 2023 · 3 comments
Labels
Milestone

Comments

@6543
Copy link
Contributor

6543 commented Aug 7, 2023

As append(append(append(a, b...), c...), d...) is way to common :/

I propose a function that gets a list of slices of same type and return one slice of that type*

// Merge return a new slice that combines all values of input slices
func Merge[T any](slices ...[]T) []T {
	sl := 0
	for i := range slices {
		sl += len(slices[i])
	}
	result := make([]T, sl)
	cp := 0
	for _, s := range slices {
		if sLen := len(s); sLen != 0 {
			copy(result[cp:], s)
			cp += sLen
		}
	}
	return result
}

test:

	resultSS := MergeSlices([]string{}, []string{"a", "b"}, []string{"c"}, nil)
	assert.EqualValues(t, []string{"a", "b", "c"}, resultSS)

	resultIS := MergeSlices([]int{}, []int{1, 2}, []int{4}, nil)
	assert.EqualValues(t, []int{1, 2, 4}, resultIS)
@6543 6543 added the Proposal label Aug 7, 2023
@6543 6543 changed the title proposal: golang.org/x/exp/slices: Add "Merge proposal: golang.org/x/exp/slices: Add "Merge" Aug 7, 2023
@gopherbot gopherbot added this to the Proposal milestone Aug 7, 2023
@6543
Copy link
Contributor Author

6543 commented Aug 7, 2023

If it will get accepted I'll file a pull :)

@ericlagergren
Copy link
Contributor

Dupe of #56353

@seankhliao
Copy link
Member

Duplicate of #56353

@seankhliao seankhliao marked this as a duplicate of #56353 Aug 7, 2023
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Aug 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants