【问题标题】:Is there a way to convert a bytes slice to a custom type of a byte array [duplicate]有没有办法将字节切片转换为自定义类型的字节数组[重复]
【发布时间】:2021-12-08 17:44:29
【问题描述】:

假设我有这样的代码:

type SomeType [16]byte

func foo(bar []byte) {
  ...
}

如何将foo() 中的bar 复制到SomeType 实例?

【问题讨论】:

  • 是的。我会关闭它。

标签: go


【解决方案1】:

从 Go 1.17 开始,您可以convert a slice to an array pointer,只要切片至少足够大以填充声明的数组。如果您希望 bar 至少为 16 个字节,这只会满足您的需求。

package main

import "fmt"

type SomeType [16]byte

func foo(bar []byte) SomeType {
    return *(*SomeType)(bar)
}

func main() {
    fmt.Println(foo([]byte("A 16 byte slice!")))                   // works
    fmt.Println(foo([]byte("A 16 byte slice and then some more"))) // works but you only access the first 16 bytes
    fmt.Println(foo([]byte("too short")))                          // panics because the underlying array is too short
}

【讨论】:

    【解决方案2】:

    使用copy,但先将数组转换为切片:

    type SomeType [16]byte
    
    func foo(bar []byte) SomeType {
        var ret SomeType
        copy(ret[:], bar)
        return ret
    }
    
    func main() {
        r := foo([]byte{1, 2, 3})
        fmt.Println(r)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-16
      • 2020-09-12
      • 2020-06-08
      • 1970-01-01
      • 2020-09-17
      • 2015-05-15
      • 2014-03-20
      • 2018-04-07
      • 1970-01-01
      相关资源
      最近更新 更多