CodeBlanks Logo Icon CodeBlanks

Slice declaration

Learn to declare dynamic arrays with slices.

Defining slices

A slice is a flexible-length view onto part of an array. Its type has no length: []int.

a := []int{1, 2, 3}      // with a literal
b := make([]int, 5)      // [0 0 0 0 0]
var c []int              // nil slice, len 0
fmt.Println(len(a), len(b), c == nil)  // 3 5 true

A slice holds three things: a pointer to the underlying array, a length (len) and a capacity (cap).

nil and empty slices

var s []int is a nil slice; s := []int{} is an empty but non-nil slice. Both have len 0, and range and append work fine on either. The difference shows in JSON: a nil slice encodes as null, an empty one as []. Slices can't be compared with == (only to nil); use slices.Equal to compare contents.

Practice Independent copy

Declare a := []int{1, 2, 3}. Make a copy with b := make([]int, len(a)) and copy(b, a), set b[0] = 99 and print a and b on one line.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    a := []int{1, 2, 3}
    b := make([]int, len(a))
    copy(b, a)
    b[0] = 99
    fmt.Println(a, b)
}

Expected output

[1 2 3] [99 2 3]

Questions and answers

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

1 After <code>b := a</code> (a is a slice), if <code>b[0] = 99</code>, what is <code>a[0]</code>?

  • A panic
  • 99; both share the same array Correct answer
  • Unchanged
  • 0

Explanation: Assigning a slice copies only its header; the underlying array is shared. For an independent copy use copy or slices.Clone.

2 Preset length

Question
puanlar := ____([]int, 3)  // [0 0 0]
Answer
puanlar := make([]int, 3)  // [0 0 0]

Explanation: make creates a slice of the given length filled with zero values.

3 Definition and result

Term Meaning
[]int{1, 2} len 2
make([]int, 3) [0 0 0]
var s []int nil, len 0
[]int{} Empty, not nil

All lessons in Beginner