Home > Backend Development > Golang > Why Doesn\'t Reflection\'s `Append` Function Update the Original Go Slice?

Why Doesn\'t Reflection\'s `Append` Function Update the Original Go Slice?

Barbara Streisand
Release: 2024-11-26 01:10:12
Original
630 people have browsed it

Why Doesn't Reflection's `Append` Function Update the Original Go Slice?

Append Function in Go Reflection

In Go, appending an element to a slice using reflection does not seem to update the original slice. This is illustrated in the following code:

func appendToSlice(arrPtr interface{}) {
    valuePtr := reflect.ValueOf(arrPtr)
    value := valuePtr.Elem()
    value = reflect.Append(value, reflect.ValueOf(55))

    fmt.Println(value.Len()) // prints 1
}

func main() {
    arr := []int{}
    appendToSlice(&arr)
    fmt.Println(len(arr)) // prints 0
}
Copy after login

Why doesn't it work?

The root cause lies in the behavior of reflect.Append. Like the conventional append function, it returns a new slice value. In this case, the value assigned to the value variable is replaced with this new slice, effectively creating a copy.

To illustrate, let's modify the example to highlight what's happening:

func appendToSlice(arrPtr *[]int) {
    value := *arrPtr
    value = append(value, 55)
    fmt.Println(len(value))
}

func main() {
    arr := []int{}
    appendToSlice(&arr)
    fmt.Println(len(arr))
}
Copy after login

This modified code produces the same output even though we're not using reflection.

Solution

To correctly append to a slice using reflection, we need to use the Value.Set method to modify the original value:

func appendToSlice(arrPtr interface{}) {
    valuePtr := reflect.ValueOf(arrPtr)
    value := valuePtr.Elem()

    value.Set(reflect.Append(value, reflect.ValueOf(55)))

    fmt.Println(value.Len())
}
Copy after login

This approach passes the newly created slice to value.Set, updating the original slice.

The above is the detailed content of Why Doesn\'t Reflection\'s `Append` Function Update the Original Go Slice?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template