dongzhang2150 2012-08-26 13:16
浏览 50
已采纳

使用指向值的指针作为切片

Is it possible to convert a pointer to certain value to a slice?

For example, I want to read single byte from io.Reader into uint8 variable. io.Reader.Read accepts a slice as its argument, so I cannot simply provide it a pointer to my variable as I'd do in C.

I think that creating a slice of length 1, capacity 1 from a pointer is safe operation. Obviously, it should be the same as creating a slice from an array of length 1, which is allowed operation. Is there an easy way to do this with plain variable? Or maybe I do not understand something and there are reasons why this is prohibited?

  • 写回答

3条回答 默认 最新

  • douchengchu8374 2012-08-26 14:33
    关注

    A slice is not only a pointer, like an array in C. It also contains the length and capacity of the data, like this:

    struct {
      ptr *uint8
      len int
      cap int
    }
    

    So, yes, you will need to create a slice. Simplest way to create a slice of the var a uint8 would be []uint8{a}

    a := uint8(42)
    fmt.Printf("%#v
    ", []uint8{a})
    

    (But after rereading your question, this is not a solution as all)

    But if you wish to create the slice from the variable, pointing to the same space of memory, you could use the unsafe package. This is most likely to be discouraged.

    fmt.Printf("%#v
    ", (*[1]uint8)(unsafe.Pointer(&a))[:] )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?