Golang将[N]字节转换为[]字节

时间:2015-03-31 07:33:04

标签: go slice

我有这段代码:

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

我收到了这个错误:

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

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

_, _ = conn.Write(h)

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

2 个答案:

答案 0 :(得分:10)

切割数组。例如,

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]

答案 1 :(得分:4)

使用数组创建切片,您只需创建simple slice expression

foo := [5]byte{0, 1, 2, 3, 4}
var bar []byte = foo[:]

或者在你的情况下:

b := md5.Sum(buffer.Bytes())
hashChannel <- b[:]
相关问题