duanguane1670 2017-11-02 05:45
浏览 244
已采纳

Golang,通过指针更改数组

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
", &arr)
    A(&arr)
    fmt.Println(arr)
}
  • 写回答

1条回答 默认 最新

  • dtnpf35197 2017-11-02 06:02
    关注

    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
    ", &arr)
        A(&arr)
        fmt.Println(arr)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 chatgpt网页版侧边栏和模型切换点击没反应怎么办
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas