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

perfect clone slice and its cap #79

Closed
fasknifer opened this issue Nov 13, 2018 · 2 comments
Closed

perfect clone slice and its cap #79

fasknifer opened this issue Nov 13, 2018 · 2 comments
Labels

Comments

@fasknifer
Copy link

fasknifer commented Nov 13, 2018

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
}
@go101
Copy link
Owner

go101 commented Nov 13, 2018

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.

	b := append(a[:0:0], a[:cap(a)]...)[:len(a):cap(a)]

@go101
Copy link
Owner

go101 commented Nov 13, 2018

You can continue to comment if you have more questions, otherwise, you can close it.

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

2 participants