douju1852
2015-03-29 22:37 阅读 197
已采纳

如何在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 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]
    }
    
    点赞 评论 复制链接分享

相关推荐