WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Slices


Go Slice is an abstraction over Go Array. Go Array lets in you to outline variables which can preserve several statistics items of the identical type but it does not offer any built in method to boom its size dynamically

Defining a slice

To define a slice, you can declare it as an array with out specifying its length. Alternatively, you may use make characteristic to create a slice.

len() and cap() capabilities

A slice is an abstraction over array. It simply makes use of arrays as an underlying structure. The len() characteristic returns the elements gives inside the slice where cap() characteristic returns the potential of the slice
bundle essential

import "fmt"

func primary() 
   var numbers = make([]int,eight,nine)
   printSlice(numbers)

func printSlice(x []int)
   fmt.Printf("len=%d cap=%d slice=%vn",len(x),cap(x),x)

When the above code is compiled and executed, it produces the following end result
$cross run major.Move
len=eight cap=nine slice=[0 0 0 0 0 0 0 0]

Nil slice

If a slice is declared with no inputs, then with the aid of default, it's far initialized as nil. Its length and ability are zero.
package deal main

import "fmt"

func foremost() 
   var numbers []int
   printSlice(numbers)
   
   if(numbers == nil)
      fmt.Printf("slice is nil")
   

func printSlice(x []int)
   fmt.Printf("len = %d cap = %d slice = %vn", len(x), cap(x),x)


When the above code is compiled and performed, it produces the subsequent result

$cross run foremost.Pass
len = zero cap = 0 slice = []
slice is nil

Subslicing

Slice permits lower-sure and higher sure to be specific to get the subslice of it the usage of[lower-bound:upper-bound]. For example

bundle predominant

import "fmt"

func fundamental() 
   /* create a slice */
   numbers := []int0,1,2,3,four,five,6,7,eight   
   printSlice(numbers)
   
   /* print the authentic slice */
   fmt.Println("numbers ==", numbers)
   
   /* print the sub slice beginning from index 1(included) to index four(excluded)*/
   fmt.Println("numbers[1:4] ==", numbers[1:4])
   
   /* lacking lower sure implies zero*/
   fmt.Println("numbers[:3] ==", numbers[:3])
   
   /* missing top bound implies len(s)*/
   fmt.Println("numbers[4:] ==", numbers[4:])
   
   numbers1 := make([]int,zero,5)
   printSlice(numbers1)
   
   /* print the sub slice beginning from index zero(blanketed) to index 2(excluded) */
   number2 := numbers[:2]
   printSlice(number2)
   
   /* print the sub slice starting from index 2(protected) to index 5(excluded) */
   number3 := numbers[2:5]
   printSlice(number3)
   

func printSlice(x []int)
   fmt.Printf("len = %d cap = %d slice = %vn", len(x), cap(x),x)


OUTPUT


<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 = nine slice = [0 1]
len = 3 cap = 7 slice = [2 3 4]