gpt4 book ai didi

Golang 将类型 [N]byte 转换为 []byte

转载 作者:IT老高 更新时间:2023-10-28 13:09:03 26 4
gpt4 key购买 nike

我有这个代码:

hashChannel <- []byte(md5.Sum(buffer.Bytes()))

我得到这个错误:

cannot convert md5.Sum(buffer.Bytes()) (type [16]byte) to type []byte

即使没有显式转换,这也不起作用。我也可以保留 [16]byte 类型,但有时我需要转换它,因为我通过 TCP 连接发送它:

_, _ = conn.Write(h)

转换它的最佳方法是什么?谢谢

最佳答案

对数组进行 slice 。例如,

package main

import (
"bytes"
"crypto/md5"
"fmt"
)

func main() {
var hashChannel = make(chan []byte, 1)
var buffer bytes.Buffer
sum := md5.Sum(buffer.Bytes())
hashChannel <- sum[:]
fmt.Println(<-hashChannel)
}

输出:

[212 29 140 217 143 0 178 4 233 128 9 152 236 248 66 126]

关于Golang 将类型 [N]byte 转换为 []byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29363055/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com