The first knowledge of go language slicing

Source: Internet
Author: User

The Go slice (Slice) is an abstraction of the go array. Since the go array allows you to define a variable of type, you can accommodate several data items of the same data type, but it does not provide any built-in method to dynamically increase its size or get its own subarray. There is no such restriction on slicing. It provides many of the practical features required for arrays and is widely used in go programming.

Defining slices

var numbers []int/* not specified size */* numbers = = []int{0,0,0,0,0}*/numbers = Make ([]int,6,6]/* length is 6 slices with 6 Capacity) */

Len () and Cap () functions

Because a slice (Slice) is an abstraction on an array. It actually uses arrays as the underlying structure. the Len () function returns the number of elements that exist in the slice, where the CAP () function returns the capacity (size) of the slice (Slice) to accommodate the number of Elements. The following is an example of the use of explanation slices (Slice):

Package main import ' FMT ' func main () {var numbers = Make ([]int,3,5) printslice (numbers)} Func printslice (x []int) {fmt. Printf ("len=%d cap=%d slice=%v\n", len (x), cap (x), x)}

When the above code compiles and executes, it produces the following results:

Len=3 cap=5 slice=[0 0 0]

Nil Slice

If no input tiles are declared by default, they are initialized to Nil. Its length and capacity are zero. The following is an example:

    

        package main                 import  "fmt"                 func main ()  {            var numbers []int                    printslice (numbers)                     if (numbers  == nil) {              fmt. Printf ("slice is nil")            }         }                 func&nbsP;printslice (x []int) {           fmt. Printf ("len=%d cap=%d slice=%v\n", len (x), cap (x), x)         }

When the above code compiles and executes, it produces the following results:

Len=0 cap=0 slice=[] Slice is nil

Child slices

Slicing (Slice) allows you to specify the lower bound and upper bounds to get its sub-slices using [low limit: Upper limit]. The following is an example:

        package main                         import   "fmt"                  Func main ()  {           /*  Create slice  */            numbers := []int{0,1,2,3,4,5,6,7,8 }              printslice (numbers)                     /*   Print this slice  */           fmt. Println ("numbers ==",  numbers)                     /*  print Sub-slice [1,4], open */           fmt before Closing. Println ("numbers[1:4] ==",  numbers[1:4])                     /*  no lower limit, default  0*/            fmt. Println ("numbers[:3] ==",  numbers[:3])                     /*  no upper limit, default slice of len*/            fmt. Println ("numbers[4:] ==",  numbers[4:])                     numbers1 := make ([]int,0,5)             printslice (numbers1)                     /*  print sub-slices  0 to 2 */            Number2 := numbers[:2]           printslice ( Number2)                     /*  Print sub-slices 2 to 5 */           number3  := numbers[2:5]           printslice (number3 )                 }                 func printslice (x  []int) {           fmt. Printf ("len=%d cap=%d slice=%v\n", len (x), cap (x), x)         }

When the above code compiles and executes, it produces the following results:

Len=9 cap=9 slice=[0 1 2 3 4 5 6 7 8] numbers = = [0 1 2 3 4 5 6 7 8] numbers[1:4] = = [1 2 3] numbers[ : 3] = = [0 1 2] numbers[4:] = = [4 5 6 7 8] len=0 cap=5 slice=[] len=2 cap=9 slice=[0 1] len=3 C Ap=7 slice=[2 3 4]

Append () and copy () functions

Slicing (Slice) allows you to increase the capacity (size) of a slice using the append () function. Use the Copy () function to copy the contents of the source slice to the target slice. The following is an example:

        package main                         import   "fmt"                  Func main ()  {           var numbers  []int           printslice (numbers)                     /*  Add an empty element to the slice  */           numbers = append ( Numbers, 0)            printslice (numbers)                     /*   Add an element to a slice */           numbers = append (numbers, 1)             printslice (numbers)                     /*  Add multiple elements */            numbers = append (numbers, 2,3,4)             printslice (numbers)                     /*  Create a new slice and increase the capacity to twice times the original * /           numbers1 := make ([]int, len ( numbers),  (cap (NUMBERS))                     /*  copy  numbers  to  numbers1 */            copy (numbers1,numbers)             printslice (numbers1)            }                 func printslice (x  []int) {           fmt. Printf ("len=%d cap=%d slice=%v\n", len (x), cap (x), x)         }

When the above code compiles and executes, it produces the following results:

Len=0 cap=0 slice=[] len=1 cap=2 slice=[0] len=2 cap=2 slice=[0 1] len=5 cap=8 slice=[0 1 2 3 4] len=5 Cap =16 slice=[0 1 2 3 4]


The first knowledge of go language slicing

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.