Last active
December 28, 2022 00:19
-
-
Save takatoshiono/3b54fdef1980e66e7b8f6766cc03e405 to your computer and use it in GitHub Desktop.
CopyDigits function ref
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// ref: https://blog.golang.org/go-slices-usage-and-internals | |
// 1234 <-- digits | |
import ( | |
"fmt" | |
"io/ioutil" | |
"regexp" | |
) | |
var digitRegexp = regexp.MustCompile("[0-9]+") | |
func CopyDigits(filename string) []byte { | |
b, _ := ioutil.ReadFile(filename) | |
b = digitRegexp.Find(b) | |
return append([]byte{}, b...) | |
} | |
func main() { | |
digits := CopyDigits("./copy-digits.go") | |
fmt.Println(digits) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@1Mark I may be wrong, but I think you can see by checking the capacity of the slice. Here's an example that focuses on that.
I used it on a plaintext version of a book, and the output shows how many bytes the original file has and how many bytes different slices have access to.
You can see that reassigning with a slice expression reduces the length, but the capacity is still as large as the whole file (712929 bytes). But if you use
append
and force it to create a new backing array, the result is 8 bytes rather than 712929.