英文:
Use pointer to a value as a slice
问题
是否可以将指向某个值的指针转换为切片?
例如,我想从io.Reader
中读取单个字节到uint8
变量中。io.Reader.Read
接受一个切片作为参数,所以我不能像在C语言中那样直接提供指向我的变量的指针。
我认为从指针创建长度为1、容量为1的切片是安全的操作。显然,这应该与从长度为1的数组创建切片相同,而这是允许的操作。是否有一种简单的方法可以使用普通变量来实现这一点?或者我可能没有理解到位,有一些原因导致这是被禁止的?
英文:
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?
答案1
得分: 2
一个切片不仅仅是一个指针,就像C语言中的数组一样。它还包含数据的长度和容量,就像这样:
struct {
ptr *uint8
len int
cap int
}
所以,是的,你需要创建一个切片。创建一个var a uint8
的最简单方法是[]uint8{a}
a := uint8(42)
fmt.Printf("%#v\n", []uint8{a})
(但是在重新阅读你的问题后,这不是一个解决方案)
但是,如果你希望从变量创建切片,指向相同的内存空间,你可以使用unsafe
包。这很可能是不被鼓励的。
fmt.Printf("%#v\n", (*[1]uint8)(unsafe.Pointer(&a))[:])
英文:
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\n", []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\n", (*[1]uint8)(unsafe.Pointer(&a))[:] )
答案2
得分: 1
为了避免(过度)复杂化这个琐碎的任务,为什么不使用简单的解决方案呢?即传递一个长度为1的切片给.Read,然后将其第一个元素赋值给你的变量。
英文:
Instead of (over)complicating this trivial task, why not to use the simple solution? I.e. pass .Read a length-1 slice and then assign its zeroth element to your variable.
答案3
得分: 1
我找到了一种方法来解决当我想要向io.Reader
提供一个变量时的情况。Go标准库真是太棒了!
import (
"io"
"encoding/binary"
)
...
var x uint8
binary.Read(reader, LittleEndian, &x)
作为一个副作用,这对于任何基本类型甚至一些非基本类型都适用。
英文:
I found a way to overcome my case when I want to supply a variable to io.Reader
. Go standard library is wonderful!
import (
"io"
"encoding/binary"
)
...
var x uint8
binary.Read(reader, LittleEndian, &x)
As a side effect this works for any basic type and even for some non-basic.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论