I was reading this blog article (last section on "A possible gotcha"), which discusses how to copy a part of a large slice into a new smaller slice so the large slice can be garbage collected.
The code they provide is:
func CopyDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
b = digitRegexp.Find(b)
c := make([]byte, len(b))
copy(c, b)
return c
}
The article suggests that there is a more concise way this function can be constructed using an append
. I'm assuming something like this, but I don't see the point of doing it this way:
func CopyDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
b = digitRegexp.Find(b)
return append(make([]byte, len(b)), b...)
}
This would also make the code less efficient since it appears that append
is implemented using copy
. Since this copying into a new slice is a fairly common operation, what's the best way to do it?