CodeBlanks Logo Icon CodeBlanks

Summary - Array and slice

Combine slice and append to write a task list.

Arrays and slices summary

Array: fixed length, a value type (copied on assignment), [3]int. Slice: flexible, a view onto an array (shared on assignment), []int; make, append, copy, s[a:b], len, cap. Rule: always assign append's result; when you need an independent copy, use copy or slices.Clone.

import "slices"

s := []int{3, 1, 2}
slices.Sort(s)                       // [1 2 3]
fmt.Println(slices.Contains(s, 2))   // true
fmt.Println(slices.Index(s, 3))      // 2

Two-dimensional slices

A table is built from a slice of slices; each row is created separately:

tablo := make([][]int, 3)
for i := range tablo {
    tablo[i] = make([]int, 3)
}
tablo[1][2] = 7
fmt.Println(tablo)  // [[0 0 0] [0 0 7] [0 0 0]]

Rows can have different lengths (a jagged table).

Practice Unique and sorted

Sort the slice []int{4, 2, 4, 1, 2, 9} with slices.Sort, then remove consecutive duplicates with slices.Compact and print the result.

Starter code

main.go
package main

import (
    "fmt"
    "slices"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "slices"
)

func main() {
    s := []int{4, 2, 4, 1, 2, 9}
    slices.Sort(s)
    s = slices.Compact(s)
    fmt.Println(s)
}

Expected output

[1 2 4 9]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the right way to delete the element at index 2 of a slice?

  • s.Remove(2)
  • s = slices.Delete(s, 2, 3) Correct answer
  • delete(s, 2)
  • s[2] = nil

Explanation: slices.Delete(s, i, j) removes the range [i, j) and returns the new slice; delete is only for maps.

2 Sort

Question
s := []int{5, 2, 8}
slices.____(s)
fmt.Println(s)  // [2 5 8]
Answer
s := []int{5, 2, 8}
slices.Sort(s)
fmt.Println(s)  // [2 5 8]

Explanation: slices.Sort sorts the slice in place in ascending order.

3 Group summary

Term Meaning
[3]int Array, fixed length
[]int Slice, flexible
append Append and assign
slices.Clone Independent copy

All lessons in Beginner