Description
This is an alternative proposal for my another one: #23905
Short description of the problem
Sometimes, we may want to merge several slices (with the same element type).
The current implementation is like:
func merge(x, y, z []T) []T {
// this make line will reset all just allocated elements.
s := make([]T, 0, len(x)+len(y) + len(z))
s = append(s, x..)
s = append(s, y...)
s = append(s, z...)
return s
}
There are two problems in the implementation:
- it is verbose.
- resetting all just allocated elements by the
make
call is unnecessary.
My original proposal thread (#23905) is closed for three possible other solutions:
- it may be implemented by custom generic
- the unnecessary element resetting may be avoided by future possible variadic argument passing enhancement.
- the unnecessary element resetting may be avoided by compiler optimizations.
However, I think the three solutions are hard to be implemented perfectly or not very practical.
- custom generic is hard to avoid the unnecessary element resetting.
- the variadic argument passing enhancement is inefficient in another way. And its readability is bad.
- compiler optimizations may be possible for some simple cases, but hard to be perfect for all cases. And it can not solve the code verbose problem.
So here I propose another alternative solution.
The solution: enhance the built-in make
function
I propose to let make
calls support the following manner:
make([]T, gap0, aSlice0, gap1, aSlice1, gap2, aSlice2, gap3, ...)
where each gapN
is an int
value, each aSliceN
is a slice with element type of T
.
Only the elements at the gap segments will be zeroed.
All gapN
can be omitted. So the following call is also valid:
make([]T, aSlice0, aSlice1, aSlice2, ...)
Omitted gaps are viewed as zero.
I think the alternative solution is both efficient and much less verbose.
============================================
Bonus for proposal (please ignore this bonus if you don't like it, I mean don't reject this main proposal by disliking the bonus):
// merge maps
make(map[K]T, aMap1, aMap2)
make(map[K]T, size, aMap1, aMap2)