github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/doc/progs/slices.go (about) 1 // compile 2 3 // Copyright 2012 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package main 8 9 import ( 10 "io/ioutil" 11 "regexp" 12 ) 13 14 func AppendByte(slice []byte, data ...byte) []byte { 15 m := len(slice) 16 n := m + len(data) 17 if n > cap(slice) { // if necessary, reallocate 18 // allocate double what's needed, for future growth. 19 newSlice := make([]byte, (n+1)*2) 20 copy(newSlice, slice) 21 slice = newSlice 22 } 23 slice = slice[0:n] 24 copy(slice[m:n], data) 25 return slice 26 } 27 28 // STOP OMIT 29 30 // Filter returns a new slice holding only 31 // the elements of s that satisfy fn. 32 func Filter(s []int, fn func(int) bool) []int { 33 var p []int // == nil 34 for _, i := range s { 35 if fn(i) { 36 p = append(p, i) 37 } 38 } 39 return p 40 } 41 42 // STOP OMIT 43 44 var digitRegexp = regexp.MustCompile("[0-9]+") 45 46 func FindDigits(filename string) []byte { 47 b, _ := ioutil.ReadFile(filename) 48 return digitRegexp.Find(b) 49 } 50 51 // STOP OMIT 52 53 func CopyDigits(filename string) []byte { 54 b, _ := ioutil.ReadFile(filename) 55 b = digitRegexp.Find(b) 56 c := make([]byte, len(b)) 57 copy(c, b) 58 return c 59 } 60 61 // STOP OMIT 62 63 func main() { 64 // place holder; no need to run 65 }