Golang: Slice of Slice
Slice of Slice
s[a:b]
-
- Return a slice of s from index a to b.
- The a is included, The b is excluded.
- The result shares the same data with original. If you modify it, the original is also modified.
s[:n]
-
Same as
s[0:n]
s[n:]
-
Same as
s[n:len(s)]
Example: Slice of Slice
package main import "fmt" func main() { var s = []int{0, 1, 2, 3} // take a slice of values var x = s[1:3] fmt.Println(x) // [1 2] }
Example: Slice of Slice Shares Data
Here's a example where modifying the slice also modifies the original.
package main import "fmt" func main() { var s = []int{0, 1, 2, 3} // take a slice var x = s[1:3] // modify it x[0] = 99 // original also changed fmt.Printf("%v\n", s) // [0 99 2 3] }
Golang, array and slice
- Golang: Array
- Golang: Slice
- Golang: Slice of Slice
- Golang: Append to Slice
- Golang: Cut Slice (Delete Elements)
- Golang: Copy Slice
- Golang: Clear Slice
- Golang: Nested Slice
- Golang: Slice of Strings to String
- Golang: Iterate Slice
- Golang: Convert Value to String
- Golang: Convert Array to Slice
- Golang: Print Slice, Array