github.com/huandu/go@v0.0.0-20151114150818-04e615e41150/doc/progs/slices.go (about)

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