Go
Below are examples of how to create a slice:
- By specifying the length and the length of the underlying array.
- By using the [low : high] expression.
Additionally, how to append
and copy
slices.
package main
import "fmt"
func main() {
// A slice of length 7 with a underlying array of length 14
x := make([]float64, 7, 14)
fmt.Println(x)
// Another way to create a slice is the [low : high] expression.
arr := [5]float64{1, 2, 3, 4, 5}
slice1 := arr[0:5]
slice2 := arr[1:4] // High index does not include the index itself
slice3 := arr[0:] // Same as arr[0:len(arr)]
slice4 := arr[:3] // Same as arr[0:3]
slice5 := arr[:] // Same as arr[0:len(arr)]
fmt.Println(slice1, slice2, slice3, slice4, slice5)
// Append
slice6 := []int{1, 2, 3}
slice7 := append(slice6, 4, 5)
fmt.Println(slice6, slice7)
// Copy
slice8 := []int{1, 2, 3}
slice9 := make([]int, 2)
copy(slice9, slice8) // Copy has two arguments. 'dst' and 'src'.
fmt.Println(slice8, slice9) // Only the first two elements are copied into slice9.
}