go - 转换 slice 的字节而不复制

标签 go

<分区>

如何在不分配新的 uint16 slice 的情况下将字节 slice 转换为 []uint16 和反向。这个问题侧重于性能和内存消耗

最佳答案

考虑 converting = copying ,除了两种特殊情况:m:=map[string]int{};m[string(bytes)) 没有分配,与 append 类似。

Using unsafe.Pointer似乎是当前的解决方法(顾名思义,“不安全”)

u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))

有一个proposal to use unsafe.Slice instead .
还有(暂时拒绝)proposal golang/go issue 13656

The problem is having to write (*[C]T)(unsafe.Pointer(v))[:n:n], for some C, T, v, and n.

A simpler way to write that entire expression would be ideal.

var s []byte = C.AsSlice((*byte)(ptr), n)

关于go - 转换 slice 的字节而不复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346167/

相关文章:

go get命令不提供输出也不生效

go - 在 Golang 中使用 goroutine 时遇到问题

windows - 在 list 列表条目中获取 : no matching manifest for windows/amd64 10. 0.18362

go - 如何从 GCP Golang SDK 检索访问 token ?

go - 检查 exec.Cmd 是否在 Go 中完成运行

http - 限制从 HTTP 响应中读取的字节数

go - 如何在 Visual Studio Code 中使用 Delve 调试器

mysql - 如何使用 go-sql-driver 创建一个新的 MySQL 数据库

go - filepath.Base 在 golang 中做什么

去 Gin : Creating generic custom validators