19. Go - Slices vs Array
Slices are arrays but without a fixed length (kind of, the array under it has a fixed length)
Slices have a capacity and a length. Capacity is the fixed length of underlying array, which increases every time the slice's length above goes above array length. Old array gets dumped into new created array plus added value of slice to form a new slice.
Slices and arrays are composite literals. Let's composite a group of values of the same type. Format: type{values}. Example: []int{1,2,3}
Slice is a reference type meaning it will pass an address of its value instead of a copy.
Slices hold pointers to an underlying array.
// y is a slice with same pointers to x's underlying array. Modifying y's elements, also modifies x's.
// use make and copy to create a new separate slice with different underlying array.
Iterating through array or slice:
for index, element := range VARIABLE {
fmt.println(element)
// this goes through the VARIABLE and prints any element.
}
Declare a slice by:
var slice []int32 // when want nothing inside when initializing
OR
var slice = []int32{} // when want to add elements inside when initializing out/in function
slice := []int32{} // when want to add elements inside when initializing in function
OR
slice := []int32{
32,42,
}
Using "make" to create slices:
// Creating slices above takes time and power because slices are built ontop of arrays.
// Using make allows efficiency if know the max capacity of our slice to create a "fixed" slice beforehand.
// Still have to use append to add more to the slice.
[0 0 0 0 0 0 0 0 0 0]
10
100
Declare array by:
var array [2]int32 // when want nothing inside
OR
var array = [2]int32{} // when want to add elements inside
OR
array := [2]int32{
32,42,
}
Append Slice:
// adding values to a slice at the end
// can add multiple values
slice1 := []int32{1,2}
slice2 := append(slice1,3,4)
Slicing Slices:
// Creating new slices using an existing slice by giving position to slice
// Slicing a slice is also a way to delete stuff from slice, finding range before and after the target and combine those sliced slices together ignoring the target.
[:INDEX] // beginning up to INDEX (not included)
[INDEX:] // INDEX to end (included)
Slice Variadic:
"..." can be used to get all values from a slice if put after the slice variable
Deleting from slice using append:
Comments
Post a Comment