douju1852 2015-03-29 22:37
浏览 248
已采纳

如何在golang中更改指针切片

I'm trying to get a better understanding of go. I created a little exercise for myself: pass a pointer slice to a function and modify it.

This is what I came up with:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    var data *[]byte
    fillData(data)
    fmt.Println((*data)[0:5])
}

func fillData(data *[]byte) {
    b := []byte("hello")
    fmt.Println(b[0:5])
    fmt.Println(string(b[0:5]))
    data = (*[]byte)(unsafe.Pointer(&b[0]))
}

But it gives an invalid memory address or nil pointer dereference error. I know I wouldn't use something like this in real code but I was just curious how to pass a slice and modify it without returning it.

https://play.golang.org/p/_K5ltKKKNV

  • 写回答

1条回答 默认 最新

  • douqiang5933 2015-03-30 03:48
    关注

    When you try to update data in fillData, you make two errors. First, you update the pointer rather than what it's pointed to. Second, data is a nil pointer, so writing through that pointer will cause a nil pointer error.

    Here's one possible way to write the code. data starts as a zero'ed slice, and gets updated inside fillData. This will copy the slice information (len, cap, and pointer to array) from b to *data which means that data will share information with b (importantly, including sharing the underlying array).

    package main
    
    import "fmt"
    
    func main() {
        var data []byte
        fillData(&data)
        fmt.Println(data, data[0:5])
    }
    
    func fillData(data *[]byte) {
        b := []byte("hello")
        *data = b[0:1]
    }
    

    Another way would be to have data being a pointer, and updating it. Then you have to pass a double pointer into fillData. That would look like this:

    package main
    
    import "fmt"
    
    func main() {
        var data *[]byte
        fillData(&data)
        fmt.Println((*data)[0:5])
    }
    
    func fillData(data **[]byte) {
        b := []byte("hello")
        *data = &b
    }
    

    Finally, the best way to write this code isn't to use pointers at all, and just return the slice. Unlike C or C++, it's rarely needed to use "output" parameters to functions. That's because go allows multiple return values.

    package main
    
    import "fmt"
    
    func main() {
        data := getData()
        fmt.Println(data, data[0:5])
    }
    
    func getData() []byte {
        return []byte("hello")[:1]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal