2023-01-04
This commit is contained in:
@@ -6,6 +6,8 @@ package main
|
|||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
|
func UNUSED(x ...interface{}) {}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// []int makes a slice, [...]int makes an array
|
// []int makes a slice, [...]int makes an array
|
||||||
x := []int{10, 20, 30}
|
x := []int{10, 20, 30}
|
||||||
@@ -59,9 +61,11 @@ func main() {
|
|||||||
z = append(z, 40)
|
z = append(z, 40)
|
||||||
fmt.Println(z, len(z), cap(z))
|
fmt.Println(z, len(z), cap(z))
|
||||||
z = append(z, 50)
|
z = append(z, 50)
|
||||||
|
|
||||||
fmt.Println(z, len(z), cap(z))
|
fmt.Println(z, len(z), cap(z))
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
|
|
||||||
|
//
|
||||||
// make specifies type, length, capacity
|
// make specifies type, length, capacity
|
||||||
|
|
||||||
// slice of ints length 5 (5 0's)
|
// slice of ints length 5 (5 0's)
|
||||||
@@ -77,4 +81,48 @@ func main() {
|
|||||||
b = append(b, 1)
|
b = append(b, 1)
|
||||||
fmt.Println(b, len(b), cap(b))
|
fmt.Println(b, len(b), cap(b))
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
|
|
||||||
|
//
|
||||||
|
// Declaring slices
|
||||||
|
// the idea is to minimise the number of times it needs to grow
|
||||||
|
|
||||||
|
// slice that is nil (use when it might stay null)
|
||||||
|
var data_nil []int
|
||||||
|
UNUSED(data_nil)
|
||||||
|
|
||||||
|
// slice that is empty (not nill)
|
||||||
|
var data_empty = []int{}
|
||||||
|
UNUSED(data_empty)
|
||||||
|
|
||||||
|
// slice literal
|
||||||
|
// useful if you have starting values/values that won't change (hardcoded)
|
||||||
|
data_literal := []int{1, 2, 3}
|
||||||
|
UNUSED(data_literal)
|
||||||
|
|
||||||
|
// slice make
|
||||||
|
// if you have an idea how large the slice should be, but not the values, use `make`
|
||||||
|
|
||||||
|
// option 1 - specify non-zero length - useful for using slices as buffers
|
||||||
|
data_option_1 := make([]int, 5)
|
||||||
|
UNUSED(data_option_1)
|
||||||
|
|
||||||
|
// option 2 - specify exact length - if you know the exact length you nneed
|
||||||
|
data_option_2 := make([]int, 10)
|
||||||
|
UNUSED(data_option_2)
|
||||||
|
|
||||||
|
// option 3 - zero length & capacity - for everything else
|
||||||
|
data_option_3 := make([]int, 0, 10)
|
||||||
|
UNUSED(data_option_3)
|
||||||
|
|
||||||
|
//
|
||||||
|
// Slicing slices
|
||||||
|
sliced := []int{1, 2, 3, 4, 5}
|
||||||
|
sliced_first_2 := sliced[:2]
|
||||||
|
sliced_skip_first := sliced[1:]
|
||||||
|
sliced_middle := sliced[2:3]
|
||||||
|
fmt.Println("slicing slices")
|
||||||
|
fmt.Println("slice:", sliced)
|
||||||
|
fmt.Println("sliced_first_2:", sliced_first_2)
|
||||||
|
fmt.Println("sliced_skip_first:", sliced_skip_first)
|
||||||
|
fmt.Println("sliced_middle:", sliced_middle)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user