Inserting Missing value NOT working GoLang

Issue

I’m trying to Insert a Int value to slice if it is missing in that.

My Code :

package main

import (
    "fmt"
)

func AppendIfMissing(slice []int, i int) []int {
    for _, ele := range slice {
        if ele == i {
            fmt.Println(i)
            return slice
        }
    }
    fmt.Println("i value is ", i)
    slice = append(slice, i)
    return slice
}

func main() {
    slice1 := []int{1, 2, 3, 4}
    AppendIfMissing(slice1, 60)
    fmt.Println("slice after adding :", slice1)
}

OutPut :

    i value is  60
    slice after adding : [1 2 3 4]

Appending to slice is not happening.What is wrong with my code ?

Solution

AppendIfMissing returns a slice which you need to affect to a variable.
append(slice, i) creates a new slice, which means the parameter slice isn’t modified, it refers to a all new slice:

  • which is returned at the end
  • which needs to be affected to a variable

    slice1 = AppendIfMissing(slice1, 60)
    

See go playground example.


I agree that the article “Arrays, slices (and strings): The mechanics of ‘append” mentions

Even though the slice header is passed by value, the header includes a pointer to elements of an array, so both the original slice header and the copy of the header passed to the function describe the same array.
Therefore, when the function returns, the modified elements can be seen through the original slice variable.

But the function in that article wasn’t using append:

func AddOneToEachElement(slice []byte) {
    for i := range slice {
        slice[i]++
    }
}

the contents of a slice argument can be modified by a function, but its header cannot

And by doing

slice = append(slice, i)

you modify the header, you reallocate the resulting slice to a completely different array.
That won’t be visible outside of the function.

Answered By – VonC

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.