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

huangapple go评论83阅读模式
英文:

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 &lt;- []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 (
	&quot;bytes&quot;
	&quot;crypto/md5&quot;
	&quot;fmt&quot;
)

func main() {
	var hashChannel = make(chan []byte, 1)
	var buffer bytes.Buffer
	sum := md5.Sum(buffer.Bytes())
	hashChannel &lt;- sum[:]
	fmt.Println(&lt;-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 &lt;- b[:]

huangapple
  • 本文由 发表于 2015年3月31日 15:33:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/29363055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定