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

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,