如何从 []byte 转换为 [16]byte?

How can I convert from []byte to [16]byte?

我有这个代码:

func my_function(hash string) [16]byte {
    b, _ := hex.DecodeString(hash)
    return b   // Compile error: fails since [16]byte != []byte
}

b 将是 []byte 类型。我知道 hash 的长度为 32。如何使上面的代码工作? IE。我可以以某种方式从通用长度字节数组转换为固定长度字节数组吗?我对分配 16 个新字节并复制数据不感兴趣。

没有将切片转换为数组的直接方法。但是,您可以复制一份。

var ret [16]byte
copy(ret[:], b)

标准库使用 []byte,如果您坚持使用其他东西,您将需要做更多的输入工作。我为我的 md5 值编写了一个使用数组的程序并后悔了。