()
| 9 | ) |
| 10 | |
| 11 | func main() { |
| 12 | // ---------------------- |
| 13 | // Declare and initialize |
| 14 | // ---------------------- |
| 15 | |
| 16 | // Create a slice with a length of 5 elements. |
| 17 | // make is a special built-in function that only works with slice, map and channel. |
| 18 | // make creates a slice that has an array of 5 strings behind it. We are getting back a 3 word |
| 19 | // data structure: the first word points to the backing array, second word is length and third |
| 20 | // one is capacity. |
| 21 | // ----- |
| 22 | // | * | --> | nil | nil | nil | nil | nil | |
| 23 | // ----- | 0 | 0 | 0 | 0 | 0 | |
| 24 | // | 5 | |
| 25 | // ----- |
| 26 | // | 5 | |
| 27 | // ----- |
| 28 | |
| 29 | // ------------------ |
| 30 | // Length vs Capacity |
| 31 | // ------------------ |
| 32 | |
| 33 | // Length is the number of elements from this pointer position we have access to (read and write). |
| 34 | // Capacity is the total number of elements from this pointer position that exist in the |
| 35 | // backing array. |
| 36 | |
| 37 | // Syntactic sugar -> looks like array |
| 38 | // It also have the same cost that we've seen in array. |
| 39 | // One thing to be mindful about: there is no value in the bracket []string inside the make |
| 40 | // function. With that in mind, we can constantly notice that we are dealing with a slice, not |
| 41 | // array. |
| 42 | slice1 := make([]string, 5) |
| 43 | slice1[0] = "Apple" |
| 44 | slice1[1] = "Orange" |
| 45 | slice1[2] = "Banana" |
| 46 | slice1[3] = "Grape" |
| 47 | slice1[4] = "Plum" |
| 48 | |
| 49 | // We can't access an index of a slice beyond its length. |
| 50 | // Error: panic: runtime error: index out of range |
| 51 | // slice1[5] = "Runtime error" |
| 52 | |
| 53 | // We are passing the value of slice, not its address. So the Println function will have its |
| 54 | // own copy of the slice. |
| 55 | fmt.Printf("\n=> Printing a slice\n") |
| 56 | fmt.Println(slice1) |
| 57 | |
| 58 | // -------------- |
| 59 | // Reference type |
| 60 | // -------------- |
| 61 | |
| 62 | // Create a slice with a length of 5 elements and a capacity of 8. |
| 63 | // make allows us to adjust the capacity directly on construction of this initialization. |
| 64 | // What we end up having now is a 3 word data structure where the first word points to an array |
| 65 | // of 8 elements, length is 5 and capacity is 8. |
| 66 | // ----- |
| 67 | // | * | --> | nil | nil | nil | nil | nil | nil | nil | nil | |
| 68 | // ----- | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | |
nothing calls this directly
no test coverage detected