Sobes.tech
Junior — Senior

Research of slice behavior and append function

livecode

Task condition

Determine what output the program will produce at each Println call, considering the details of how the append function, slices, and their capacity work.

package main

import "fmt"

func main() {
 slice := make([]string, 0, 5)
 slice = append(slice, "0")
 slice = append(slice, "1")
 slice = append(slice, "2")
 slice = append(slice, "3")
 fmt.Println(slice, len(slice), cap(slice)) // ?

 addToSlice1(slice)
 fmt.Println(slice, len(slice), cap(slice)) // ?

 addToSlice2(slice)
 fmt.Println(slice, len(slice), cap(slice)) // ?
}

func addToSlice1(slice []string) {
 slice = append(slice[:1:1], "one")
}

func addToSlice2(slice []string) {
 slice = append(slice, "two")
}