Sub-slice
- Go course
- Beginner
- Lesson 44/90
- 4 min
Learn the slice slicing syntax.
Sub-slices
The expression s[start:end] gives a sub-slice from index start up to, but not including, index end. Either bound can be omitted:
s := []string{"a", "b", "c", "d", "e"}
fmt.Println(s[1:3]) // [b c]
fmt.Println(s[:2]) // [a b]
fmt.Println(s[3:]) // [d e]A sub-slice doesn't create a new array; it shares the same one. Changing the sub-slice changes the original too.
The sharing trap
Appending to a sub-slice overwrites the original slice's next elements if there is capacity:
s := []int{1, 2, 3, 4}
ilk := s[:2] // [1 2], cap 4
ilk = append(ilk, 99)
fmt.Println(s) // [1 2 99 4] ← 3 was overwritten!To prevent this, three-index slicing limits the capacity: s[:2:2]. Then append allocates a new array.
Practice Middle elements
Declare s := []int{1, 2, 3, 4, 5}. Take orta := s[1:4], set orta[0] = 20 and print both orta and s on one line (see the sharing).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
s := []int{1, 2, 3, 4, 5}
orta := s[1:4]
orta[0] = 20
fmt.Println(orta, s)
}Expected output
[20 3 4] [1 20 3 4 5]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For <code>s := []int{10, 20, 30, 40}</code>, what is <code>s[1:3]</code>?
- [10 20 30]
- [20 30 40]
- [30]
- [20 30] Correct answer
Explanation: The start is included, the end excluded: indexes 1 (20) and 2 (30).
2 Last two elements
s := []string{"a", "b", "c", "d"}
son := s[____] // [c d]
s := []string{"a", "b", "c", "d"}
son := s[2:] // [c d]
Explanation: s[2:] gives the elements from index 2 to the end.
3 Expression and result (s = [a b c d e])
| Term | Meaning |
|---|---|
s[1:3] |
[b c] |
s[:2] |
[a b] |
s[3:] |
[d e] |
s[:] |
[a b c d e] |