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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?