1

I have some arrays of different struct, and I need to change them by the same function func foo(arr interface{}).

And I use the function in this way foo(&arrayToChange)

Then I find that, I cannot change the array by pointer a simple example for you.

package main

import (
    "fmt"
)

func A(out interface{}) {
    arr := make([]interface{}, 0)
    arr = append(arr, "foo", 2.2)
    out = &arr
    B(out)
}

func B(out interface{}) {
    arr := make([]interface{}, 0)
    arr = append(arr, "bar", "foo", "anything")
    out = &arr
}

func main() {
    arr := make([]interface{}, 0)
    arr = append(arr, 1, 2, 3)
    fmt.Printf("%T\n", &arr)
    A(&arr)
    fmt.Println(arr)
}

1 Answer 1

5

I guess your question there is, even though you do out = &arr inside the function, how come arr in the caller is unchanged.

out is a local variable in your function. You pass to the function &arr, so the value of out is the address of arr. And then you change the value of out to something else. This affects nothing outside the scope of this function. Reassigning the values of local variables never affects anything outside the scope of a function.

It seems what you're trying to do is something like this:

*out = arr

That is, change the value where out is pointing.

package main

import (
    "fmt"
)

func A(out *[]interface{}) {
    arr := make([]interface{}, 0)
    arr = append(arr, 1, 2)
    *out = arr
}

func main() {
    arr := make([]interface{}, 0)
    arr = append(arr, 1, 2, 3)
    fmt.Printf("%T\n", &arr)
    A(&arr)
    fmt.Println(arr)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this answer works on []int. But I got invalid indirect of out (type interface {}) when i try use it on interface{}. What I really want is to write a general function which can set/update the value of a pointer.
Caused by the preconception that []interface{} is illegal in Golang, I never once thought I can try *[]interface{}. It's just a little bit difficult to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.