Go course

SlicesSlicing: Cutting a Slice

Go

Display

Theme

Slices · Test exercise

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:

  1. func halaman(pesan []string, nomor, ukuran int) []string: return the messages on page number nomor (starting from 1), each page holding ukuran messages. The last page may hold fewer messages. If nomor < 1, ukuran < 1, or the page lies beyond the data, return an empty slice (nil is fine too).
  2. func terbaru(pesan []string, n int) []string: the last n messages. If n is larger than the number of messages, return all of them. If n <= 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].

main.go
package main

import "fmt"

func halaman(pesan []string, nomor, ukuran int) []string {
	// TODO: hitung indeks awal dan akhir lalu potong slice
	return pesan
}

func terbaru(pesan []string, n int) []string {
	// TODO
	return pesan
}

func main() {
	riwayat := []string{"halo", "apa kabar?", "baik", "lagi di mana?", "di kafe", "otw"}
	fmt.Println(halaman(riwayat, 2, 4))
	fmt.Println(terbaru(riwayat, 3))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)