Go Slices

“keep it mind that Slices part of Arrays, when we create Slice, in the backgroud automaticly Go creates an array, and assignt our Slice as a part of this array”

 

Slices are very similar to Arrays, but more flexible.  we can create a slice basicly 3 ways

1 – commun way -> just like a Array but with out length
mySlice=  []int{1,2} // any time we can change length of slice by adding elements.


2- creating from an array

arr1 := [4]int{1234} // an array with 4 elements
myslice := arr1[1:3] // our slice take a 2 elements form our array as a element

IMPORTANT here 1 is index1 until Index3 but intex3 is not included 
myslice elements are 2 and 3
This way we can decrese or increse elements of our Slice. But we are depenting always on our Array in this case

3- Creating slices using make() function 

slice_name := make([]typelengthcapacity)

myslice1 := make([]int510)
5 length of Slice 10 is  capacity

 

Manipulating Slices 

we can modify elements in Slices like an array just indicating index-number and assign new values
slice := []int{1,2,3} // OUTPUT 1 2 3
slice[0] = 5 // NOW output 5 2 3

we can also create new slice grouping 2 existing slices to gether
sliceOne := []int{1,2,3}
sliceTwo := []int{4,5,6}
sliceGrouped := append(sliceOne, sliceTwo…) // … <- 3 points indicate grouping operation

 

increacing capacity and Length of Slices

We can add new elements in to slice as you see below

myslice :=[]int{1,2,3} // Slice with 3 elements
myslice = append(myslice,4, 5, 6, 7) // adding 4 more elements to slice