On Wed, May 28, 2025 at 10:41 AM Сергей Пилипенко <territhi...@gmail.com> wrote: > > Hello, gophers! > > I have attempted to use the copy function for slices and found it’s API a bit > strange. Suppose I have two slices: one of size 0 and capacity 10, the other > of size 10 and capacity 10. When I copy the second one into the first one > nothing happens, because the length of the first size is 0, although it could > hold the elements just fine. > > So, I am wondering why isn’t copying limited by the capacity of the > destination slice instead? It doesn’t look natural for me to have to pad the > slice with the default values of the type, as they will be overwritten by the > copy anyway.
The slice length as the limit for copy is the sensible choice here because it is a constant time operation to reslice within the slice capacity. So: slice:=make([]byte,0,10) copy(slice[:5],source) is valid and efficient. You don't need to pad the slice, you can just slice the existing slice to any length within the capacity. If slice capacity was the choice instead, you would have to allocate the correct length slice whenever there is size mismatch, > > Thank you for the time! > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion visit > https://groups.google.com/d/msgid/golang-nuts/0447e9ef-2daa-4fe5-b1b6-b05a5caeafeb%40Spark. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/CAMV2RqqOuF1N821H9fGMqJJLH-8vBs44gkd0HgWfEiboD0-%3DEg%40mail.gmail.com.