Slicing: Cutting a Slice
The expression s[awal:akhir] creates a new slice holding the elements from index awal (start) up to, but not including, akhir (end):
huruf := []string{"a", "b", "c", "d", "e"}
fmt.Println(huruf[1:4]) // [b c d]
fmt.Println(huruf[:2]) // [a b] — awal default 0
fmt.Println(huruf[3:]) // [d e] — akhir default len(huruf)
fmt.Println(huruf[:]) // [a b c d e]
If you leave out the start it defaults to 0, and if you leave out the end it defaults to the slice's length. The result's length is akhir - awal. An index out of bounds causes a panic, so make sure 0 <= awal <= akhir <= len(s).
The built-in min and max functions (Go 1.21+) are handy for "clamping" a bound:
akhir := min(10, len(huruf)) // 5
Sharing the same array
The result of slicing doesn't copy the data; it points to the same array. Changing an element in the cut also changes the original slice:
nilai := []int{70, 80, 90}
awal := nilai[:2]
awal[0] = 100
fmt.Println(nilai) // [100 80 90]
If you need a truly separate copy, use copy or slices.Clone (covered later).
Task
A chat app shows message history one page at a time. Complete:
func halaman(pesan []string, nomor, ukuran int) []string: return the messages on page numbernomor(starting from 1), each page holdingukuranmessages. The last page may hold fewer messages. Ifnomor < 1,ukuran < 1, or the page lies beyond the data, return an empty slice (nilis fine too).func terbaru(pesan []string, n int) []string: the lastnmessages. Ifnis larger than the number of messages, return all of them. Ifn <= 0, return an empty slice.
Use slicing (s[a:b]), not a loop.
Example with pesan = [p1 p2 p3 p4 p5]: halaman(pesan, 2, 2) → [p3 p4], halaman(pesan, 3, 2) → [p5], terbaru(pesan, 2) → [p4 p5].