英文:
Golang convert type [N]byte to []byte
问题
我有这段代码:
hashChannel <- []byte(md5.Sum(buffer.Bytes()))
然后我得到了这个错误:
无法将md5.Sum(buffer.Bytes())(类型为[16]byte)转换为类型[]byte
即使没有显式转换,这也不起作用。我也可以保留类型[16]byte,但在某个时候我需要将其转换,因为我要通过TCP连接发送它:
_, _ = conn.Write(h)
最佳的转换方法是什么?
谢谢。
英文:
I have this code:
hashChannel <- []byte(md5.Sum(buffer.Bytes()))
And I get this error:
cannot convert md5.Sum(buffer.Bytes()) (type [16]byte) to type []byte
Even without the explicit conversion this does not work. I can keep the type [16]byte as well, but at some point I need to convert it, as I'm sending it over a TCP connection:
_, _ = conn.Write(h)
What is the best method to convert it?
Thanks
答案1
得分: 15
切片数组。例如,
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]
英文:
Slice the array. For example,
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)
}
Output:
[212 29 140 217 143 0 178 4 233 128 9 152 236 248 66 126]
答案2
得分: 8
使用数组创建切片可以使用简单的切片表达式:
foo := [5]byte{0, 1, 2, 3, 4}
var bar []byte = foo[:]
或者在你的情况下:
b := md5.Sum(buffer.Bytes())
hashChannel <- b[:]
英文:
Creating a slice using an array you can just make a simple slice expression
:
foo := [5]byte{0, 1, 2, 3, 4}
var bar []byte = foo[:]
Or in your case:
b := md5.Sum(buffer.Bytes())
hashChannel <- b[:]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论