Sobes.tech
Middle+

Task: What will the code output? ```go package main import "fmt" func main() { a := []int{1, 2, 3, 4, 5} b := a[:2] b = append(b, 100) fmt.Println(a, b) } ```

sobes.tech AI

Answer from AI

Code:

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4, 5}
    b := a[:2]       // b references the first two elements of a: [1, 2]
    b = append(b, 100) // add 100 to slice b
    fmt.Println(a, b)
}

Analysis:

  • Initially, a = [1, 2, 3, 4, 5]
  • b := a[:2] — slice b contains [1, 2], and its capacity is 5 (from index 0 to the end of a)
  • append(b, 100) adds the element 100 to slice b. Since b's capacity allows expansion without allocating new memory, the element 100 is written into a[2], thus modifying the original array a.

After append:

  • a becomes [1, 2, 100, 4, 5]
  • b becomes [1, 2, 100]

Output:

[1 2 100 4 5] [1 2 100]

This means the element a[2] changed from 3 to 100 because b and a share the same underlying array.

Task: What will the code output? ```go package main… - sobes.tech