mirror of
https://github.com/golang/go
synced 2024-11-17 21:54:49 -07:00
9443949207
Originally published on the Go blog on 5 Jan 2011: http://blog.golang.org/2011/01/go-slices-usage-and-internals.html R=golang-dev, gri CC=golang-dev https://golang.org/cl/5516046
56 lines
979 B
Go
56 lines
979 B
Go
package main
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"regexp"
|
|
)
|
|
|
|
func AppendByte(slice []byte, data ...byte) []byte {
|
|
m := len(slice)
|
|
n := m + len(data)
|
|
if n > cap(slice) { // if necessary, reallocate
|
|
// allocate double what's needed, for future growth.
|
|
newSlice := make([]byte, (n+1)*2)
|
|
copy(newSlice, slice)
|
|
slice = newSlice
|
|
}
|
|
slice = slice[0:n]
|
|
copy(slice[m:n], data)
|
|
return slice
|
|
}
|
|
|
|
// STOP OMIT
|
|
|
|
// Filter returns a new slice holding only
|
|
// the elements of s that satisfy f()
|
|
func Filter(s []int, fn func(int) bool) []int {
|
|
var p []int // == nil
|
|
for _, i := range s {
|
|
if fn(i) {
|
|
p = append(p, i)
|
|
}
|
|
}
|
|
return p
|
|
}
|
|
|
|
// STOP OMIT
|
|
|
|
var digitRegexp = regexp.MustCompile("[0-9]+")
|
|
|
|
func FindDigits(filename string) []byte {
|
|
b, _ := ioutil.ReadFile(filename)
|
|
return digitRegexp.Find(b)
|
|
}
|
|
|
|
// STOP OMIT
|
|
|
|
func CopyDigits(filename string) []byte {
|
|
b, _ := ioutil.ReadFile(filename)
|
|
b = digitRegexp.Find(b)
|
|
c := make([]byte, len(b))
|
|
copy(c, b)
|
|
return c
|
|
}
|
|
|
|
// STOP OMIT
|