Go Learning notes: slices

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Slices are one of the key types of the go language and provide more functionality than arrays.

Example 1:

package mainimport  "FMT" Func main ()  {    //  and arrays are different, the length of the slices is variable.     //  We can use built-in function make to create a non-zero-length slice     //  Here we've created a length of 3, The slice that stores the string, the slice element     //  default is a zero value, and the string is "".     s := make ([]string, 3)     fmt. Println ("EMP:",  s)     //  can use an array of methods to set element values or get element values     s[0]  =  "A"     s[1] =  "B"     s[2] =  "C"      fmt. Println ("Set:",  s)     fmt. Println ("Get:",  s[2])     //  the length of the slice     fmt can be obtained with the built-in function Len. Println ("Len:",  len (s))     //  slices also have some functionality that the array does not have.     //  For example, we can use the built-in function append to append a value to a slice, and then     //  return a slice with the new slice element.     //  Note that the APPEND function does not change the original slice, but instead generates a new slice, &Nbsp;   //  we need to use the original slice to receive the new slice     s = append (s,  "D")     s = append (s,  "E",  "F")     fmt. Println ("APD:",  s)     //  In addition we can copy elements from one slice to another slice     //  The following example creates a new slice with the same length as the slice s     //  and then uses the built-in copy function to copy the elements of S into C.     c := make ([]string, len (s))     copy (c, s)     fmt. Println ("cpy:",  c)     //  slices also supports a slice-taking operation   "Slice[low:high]"      //  gets a new slice that contains the element "Slice[low", but does not contain "Slice[high"     //  The following example takes a new slice, the element includes "S[2" "," s[3] "," s[4] ".     l := s[2:5]    fmt. Println ("SL1:",  l)     //  if Low is omitted, the default starting from 0, excluding the "Slice[high" element      l = s[:5]    fmt. PRINTLN ("SL2: ",  l)     //  If High is omitted, the default is Len (slice), including the" Slice[low] "element     l  = s[2:]    fmt. Println ("SL3:",  l)     //  We can declare and initialize a slice at the same time     t :=  []string{"G",  "H",  "I"}    fmt. Println ("DCL:",  t)     //  We can also create multidimensional slices, and arrays are different, and the length of the slice elements is also variable.     twod := make ([][]int, 3)     for i :=  0; i < 3; i++ {        innerlen  := i + 1        twod[i] = make ([]int,  innerlen)         for j := 0; j <  innerlen; j++ {            twod[i] [J] = i + j   &nbsP;    }    }    fmt. Println ("2d: ",  twod)}

Output Result:

EMP: []set: [a b] C]GET:CLEN:3APD: [a b c d e f]cpy: [a b c d e F]SL1: [C D E]SL2: [a b C D E]SL3: [C D e F]DCL: [g H i ]2d: [[0] [1 2] [2 3 4]]

The difference between how arrays and slices are defined is [] whether or not the 固定长度 length marker is inferred ... .


Example 2:

Package Mainimport "FMT" Func Main () {s1: = make ([]int, 0) test (S1) fmt. Println (S1)}//value func test (s []int) {s = append (s, 3)///Because the original allocated space is not enough, so the space is redistributed at another address, so the data of the original address is not changed}

Output Result:

[]//Empty array

Package Mainimport "FMT" Func Main () {s1: = make ([]int, 0) S1 = Test (S1) fmt. Println (S1)}func test (s []int) []int {s = append (S, 3) return s}

Output Result:

[3]//Correct results


Example 3:

cap is the maximum capacity of the slice, and the Append function adds elements that, if they exceed the original slice capacity, redistribute the underlying array.

Package Mainimport "FMT" Func Main () {s1: = make ([]int, 3, 6) fmt. Println ("s1=", S1, Len (S1), Cap (S1)) S2: = Append (S1, 1, 2, 3) fmt. Println ("s1=", S1, Len (S1), Cap (S1)) Fmt. Println ("s2=", S2, Len (S2), Cap (S2)) S3: = Append (s2, 4, 5, 6) fmt. Println ("s1=", S1, Len (S1), Cap (S1)) Fmt. Println ("s2=", S2, Len (S2), Cap (S2)) fmt. Println ("s3=", S3, Len (S3), Cap (S3))}

Output Result:

s1= [0 0 0] 3 6s1= [0 0 0] 3 6s2= [0 0 0 1 2 3] 6 6s1= [0 0 0] 3 6s2= [0 0 0 1 2 3] 6 6s3= [0 0 0 1 2 3 4 5 6] 9 12


Example 4:

When you point to the slice of the same underlying array, the copy is allowed to overlap. When you copy an array, the minimum length is limited by the SRC and DST arrays.

Package Mainimport "FMT" Func Main () {s1: = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} s2: = make ([]int, 3,] var n in T n = copy (s2, s1) fmt. PRINTLN (n, S2, len (S2), Cap (S2)) S3: = S1[4:6] FMT. PRINTLN (N, S3, Len (S3), Cap (s3)) n = copy (s3, S1[1:5]) fmt. PRINTLN (N, S3, Len (S3), Cap (S3))}

Output Result:

3 [0 1 2] 3 203 [4 5] 2 62 [1 2] 2 6



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.