93
func main(){
     var array [10]int
     sliceA := array[0:5]
     append(sliceA, 4)
     fmt.Println(sliceA)
}

Error : append(sliceA, 4) evaluated but not used

I don't Know why? The slice append operation is not run...

Kaushik
  • 2,072
  • 1
  • 23
  • 31
L.jerson
  • 933
  • 1
  • 6
  • 6

5 Answers5

134

Refer: Appending to and copying slices

In Go, arguments are passed by value.

Typical append usage is:

a = append(a, x)

You need to write:

func main(){
    var array [10]int
    sliceA := array[0:5]
    // append(sliceA, 4)  // discard
    sliceA = append(sliceA, 4)  // keep
    fmt.Println(sliceA)
}

Output:

[0 0 0 0 0 4]
starball
  • 20,030
  • 7
  • 43
  • 238
Mohsin Aljiwala
  • 2,457
  • 2
  • 23
  • 30
  • Would be nice to know why a return value is necessary. I'm assuming it's because you could do `sliceB := append(sliceA, 4)` without changing sliceA. In contrast, delete() modifies in place https://stackoverflow.com/a/71691201/722796 – PJ Brunet May 31 '23 at 20:35
15
sliceA = append(sliceA, 4)

append() returns a slice containing one or more new values.
Note that we need to accept a return value from append as we may get a new slice value.

Muhammad Tariq
  • 3,318
  • 5
  • 38
  • 42
榴莲榴莲
  • 151
  • 3
4

you may try this:

sliceA = append(sliceA, 4)

built-in function append([]type, ...type) returns an array/slice of type, which should be assigned to the value you wanted, while the input array/slice is just a source. Simply, outputSlice = append(sourceSlice, appendedValue)

Nevercare
  • 81
  • 3
2

Per the Go docs:

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

So the return value of 'append', will contain your original slice with the appended portion.

djt
  • 7,297
  • 11
  • 55
  • 102
1

The key to understand is that slice is just a "view" of the underling array. You pass that view to the append function by value, the underling array gets modified, at the end the return value of append function gives you the different view of the underling array. i.e. the slice has more items in it

your code
sliceA := array[0:5]  // sliceA is pointing to [0,5)
append(sliceA, 4) // sliceA is still the original view [0,5) until you do the following

sliceA = append(sliceA, 4)

reference: https://blog.golang.org/slices

hefeicoder
  • 123
  • 1
  • 7