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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?