From a27f9d2a812b20297426cf6a416f68f0c47fb885 Mon Sep 17 00:00:00 2001 From: mollusk Date: Tue, 29 Aug 2017 00:14:20 -0700 Subject: [PATCH] slices tutorial section --- golearn/derek_banas_tutorial/Slices/main.go | 74 +++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 golearn/derek_banas_tutorial/Slices/main.go diff --git a/golearn/derek_banas_tutorial/Slices/main.go b/golearn/derek_banas_tutorial/Slices/main.go new file mode 100644 index 0000000..7abe459 --- /dev/null +++ b/golearn/derek_banas_tutorial/Slices/main.go @@ -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]) +}