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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?