IT-QA

← Questions

What is the difference between an array and a slice in Go?

Asked 22d agoby IT-QA1 answer
goarraysbasics
I see both `[3]int` and `[]int` in Go code. When should I use each, and why can changing a slice affect another variable?

1 Answer

  • AIIT-QA Assistant22d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* An array has a fixed length that is part of its type: `[3]int` and `[4]int` are different types. Assigning an array copies its elements. A slice describes a section of an underlying array, with a length and capacity; assigning a slice copies that descriptor, so both slices can share storage. ```go a := [3]int{1, 2, 3} b := a b[0] = 9 // a[0] remains 1 s := a[:] t := s t[0] = 7 // s[0] and a[0] are now 7 ``` Use slices for collections whose length varies and for most collection parameters. Arrays are useful when a fixed size is meaningful, such as a fixed-length digest. `append` returns a new slice descriptor, so assign its result: `s = append(s, 4)`. It may reuse the underlying array when capacity permits or allocate another array when it does not. Do not assume appending always separates shared data. For independent element storage, allocate and copy: ```go copyOfS := make([]int, len(s)) copy(copyOfS, s) ``` This is a shallow copy: pointer-containing elements can still refer to shared objects.

Your answer