5 Matching Annotations
  1. Dec 2022
    1. For example, this FindDigits function loads a file into memory and searches it for the first group of consecutive numeric digits, returning them as a new slice. ``` var digitRegexp = regexp.MustCompile("[0-9]+")

      func FindDigits(filename string) []byte { b, _ := ioutil.ReadFile(filename) return digitRegexp.Find(b) } This code behaves as advertised, but the returned []byte points into an array containing the entire file. Since the slice references the original array, as long as the slice is kept around the garbage collector can’t release the array; the few useful bytes of the file keep the entire contents in memory. To fix this problem one can copy the interesting data to a new slice before returning it: func CopyDigits(filename string) []byte { b, _ := ioutil.ReadFile(filename) b = digitRegexp.Find(b) c := make([]byte, len(b)) copy(c, b) return c } ```

    2. slice = slice[0:n]

      // 只取 m+n 位长度的slice,而不是返回整个扩展后的 newSlice

    1. The length of a slice is the number of elements it contains. ↳ The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice. ↳ The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).

      len(slice []type) cap(slice []type)

  2. Nov 2021
  3. Oct 2021
    1. It’s important to understand that even though a slice contains a pointer, it is itself a value. Under the covers, it is a struct value holding a pointer and a length. It is not a pointer to a struct.

      slice 是一个包含指针的结构体,他是一个具体值而不是指针