Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang append() evaluated but not used

Tags:

arrays

var

go

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...

like image 780
L.jerson Avatar asked Jul 10 '17 06:07

L.jerson


3 Answers

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]

I hope it helps.

like image 101
Mohsin Avatar answered Nov 15 '22 11:11

Mohsin


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.

like image 30
榴莲榴莲 Avatar answered Nov 15 '22 11:11

榴莲榴莲


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)

like image 4
Nevercare Avatar answered Nov 15 '22 11:11

Nevercare