You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import "fmt"
func CloneSlice(a []int) []int {
return append(a[:0:0], a...)
}
func main() {
a := make([]int, 3, 5)
b := CloneSlice(a)
fmt.Printf("cap of a is %v\n", cap(a))
fmt.Printf("cap of b is %v\n", cap(b))
}
the result:
cap of a is 5
cap of b is 4
Is there a way to perfectly clone slice and its cap? (in short form)
A known but not short way:
func CloneSlice(a []int) []int {
if nil == a {
return nil
}
b := make([]int, len(a), cap(a))
copy(b, a)
return b
}
The text was updated successfully, but these errors were encountered:
Ah, I haven't found a way to clone a slice and assure the result slice has the same capacity with the cloned slice. But I have a way to assure the capacity of the result slice is larger than the cloned slice.
b:=append(a[:0:0], a[:cap(a)]...)[:len(a)]
If you do want the capacity of the result slice is exactly the same as the cloned slice, then you can use the following line, though I recommend the above one over the following line, for the following line is some kind of memory leaking.
the result:
cap of a is 5
cap of b is 4
Is there a way to perfectly clone slice and its cap? (in short form)
A known but not short way:
The text was updated successfully, but these errors were encountered: