Go (golang) Tutorials - Slices (Part 1)

Published: 26 March 2018
on channel: Ambasoft Java
275
9

#golang #go #slices

Slices - An abstraction over the static arrays, using which we can perform dynamic operations on the arrays
--------
1. Creating a slice with its length specified
2. Declare slice with slice literal
3. nil slice
4. empty slice
5. slice of slices
a) Slice A with a set of values
b) Slice B from slice A
c) Perform operations and access on Slice B and let us see how it affects Slice A
6. Length & capacity
7. Effects of making changes to a slice
Every change happening in the new slice will have corresponding change reflected in the source slice

slicedemo.go
-----------

package main
import "fmt"
func main(){
//Slice - 1.Pointer, 2.length, 3.capacity
var a []int //Declare a variable "a" which is an integer slice - Pointer will be nil - nil slice
b:=make([]int,5) //Declaration as well as instantiation of a new slice b of type integer
c:=make([]int,0) //Slice Instantiation - Pointer will be pointing to a new address for the slice - Empty slice
d:=[]int{10,20,30,40,50} //Go compiler dynamically identifies the length of the slice "d" based on the number of values we initialize
fmt.Printf("The length of a is %d, The length of b is %d, The length of c is %d, the length of d is %d\n",len(a),len(b),len(c),len(d))

}

slicetest.go
--------------
package main
import "fmt"
func main(){
x:=make([]int,5,7) //Capacity for a slice should always be smaller or equal to the slice length
a:=[]int { 100,200,300,400,500} //0-100,1-200,2-300,3-400,4-500
b:=a[1:3] // Create a new slice "b" from an existing slice "a" from the index[1:] 1 upto the length of the slice is the capacity of b. The length is [:3] which means, until the third
//index of slice a should be the length of slice b
fmt.Printf("The length of a is %d, the capacity of a is %d\n",len(a),cap(a))
fmt.Printf("The length of x is %d, the capacity of x is %d\n",len(x),cap(x))
fmt.Printf("The length of b is %d, the capacity of b is %d\n",len(b),cap(b))
b[1]=1000 //b[0] is pointing to a[1]. changes to b[0] or any index of b will have a corresponding change gets reflected in "a"
//Use For loop
fmt.Println(a[i])

}


Watch video Go (golang) Tutorials - Slices (Part 1) online, duration hours minute second in high quality that is uploaded to the channel Ambasoft Java 26 March 2018. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 275 times and liked it 9 visitors.