slices tutorial section
This commit is contained in:
parent
dd8d5e6b72
commit
a27f9d2a81
74
golearn/derek_banas_tutorial/Slices/main.go
Normal file
74
golearn/derek_banas_tutorial/Slices/main.go
Normal file
@ -0,0 +1,74 @@
|
||||
/*
|
||||
Slices: https://www.youtube.com/watch?v=CF9S4QZuV30&t=1139s#
|
||||
Syntax: 0:3 - a slice capturing the first index up to then 3rd index
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
/*
|
||||
A slice is like an array but when you define them
|
||||
you leave out the size
|
||||
*/
|
||||
|
||||
//define an array without a static size of type 'int' and assign values
|
||||
numSlice := []int{5, 4, 3, 2, 1}
|
||||
|
||||
/*
|
||||
define a variable containing the pre-created array and
|
||||
start at the 3rd index going through the 5th
|
||||
(Indexes start at 0 here as well)
|
||||
*/
|
||||
numSlice2 := numSlice[3:5]
|
||||
|
||||
fmt.Println("numSlice2[0] =", numSlice2[0])
|
||||
fmt.Println("numSlice2[1] =", numSlice2[1])
|
||||
|
||||
/*
|
||||
If you do not supply the first number before the colon
|
||||
the first number will default to index (0)
|
||||
the result is everyting before index 2
|
||||
*/
|
||||
fmt.Println("numSlice[:2] =", numSlice[:2])
|
||||
|
||||
/*
|
||||
The opposite is true if you do not supply the second number
|
||||
the result is everything after index 2
|
||||
*/
|
||||
fmt.Println("numSlice[2:] =", numSlice[2:])
|
||||
|
||||
/*
|
||||
To create a slice without set values, you need to use 'make'
|
||||
If you want index 0 to start at index 5 and set a max
|
||||
length of 10:
|
||||
*/
|
||||
|
||||
numSlice3 := make([]int, 5, 10)
|
||||
|
||||
/*
|
||||
numSlice3 at this point is empty since no values were assigned
|
||||
but we can copy the values of numSlice with 'copy'
|
||||
*/
|
||||
copy(numSlice3, numSlice)
|
||||
|
||||
/*
|
||||
Since numSlice3 begins at index 5, index 0 will output the
|
||||
5th index of 'numSlice' which was copied into numSlice3
|
||||
*/
|
||||
fmt.Println("numSlice3[0] =", numSlice3[0])
|
||||
fmt.Println("numSlice3[1] =", numSlice3[1])
|
||||
|
||||
/*
|
||||
Since we gave numSlice3 a maximum of 10 possible indexes
|
||||
we can append more values than the original 'numSlice' variable
|
||||
which was only 5 indexes originally
|
||||
*/
|
||||
|
||||
//append the values '0', and '-1' to the next available indexes ( 5 and 6)
|
||||
numSlice3 = append(numSlice3, 0, -1)
|
||||
|
||||
fmt.Println("numSlice3[5] =", numSlice3[5])
|
||||
fmt.Println("numSlice3[6] =", numSlice3[6])
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user