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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?