go函数返回数组

Defining a function that returns a slice of variable size in golang

First of all, slices are already of “variable size”: [100]int and […]int are array type definitions.
[]int is the correct syntax for a slice, and you could implement the function as:

func BuildSlice(size int) []int {
    return make([]int, size)
}
The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

Call             Type T     Result

make(T, n)       slice      slice of type T with length n and capacity n
make(T, n, m)    slice      slice of type T with length n and capacity m

The size arguments n and m must be of integer type or untyped. A constant size argument must be non-negative and representable by a value of type int. If both n and m are provided and are constant, then n must be no larger than m. If n is negative or larger than m at run time, a run-time panic occurs.

s := make([]int, 10, 100)       // slice with len(s) == 10, cap(s) == 100
s := make([]int, 1e3)           // slice with len(s) == cap(s) == 1000
s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int s := make([]int, 10, 0) // illegal: len(s) > cap(s)
func obtainNext(str string) []int {
   sLen := len(str)
   next := make([]int, sLen)
   next[0] = -1
   k, j := -1, 0
   for j < sLen-1 {
      if k == -1 || str[j] == str[k] {
         k++
         j++
         next[j] = k
      } else {
         k = next[k]
      }
   }
   return next
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.