【问题标题】:Golang convert type [N]byte to []byte [duplicate]Golang将类型[N]byte转换为[]byte [重复]
【发布时间】:2015-06-04 11:06:28
【问题描述】:

我有这个代码:

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

我得到这个错误:

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

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

_, _ = conn.Write(h)

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

【问题讨论】:

  • [:] 将数组转换为切片

标签: go slice


【解决方案1】:

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

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

或者在你的情况下:

b := md5.Sum(buffer.Bytes())
hashChannel <- b[:]

【讨论】:

  • BUG:hashChannel &lt;- md5.Sum(buffer.Bytes())[:] 错误是invalid operation md5.Sum(buffer.Bytes())[:] (slice of unaddressable value)
  • peterSo:啊,是的。对此感到抱歉。确实是错误。更正了
  • @ANisus 你知道为什么我们需要引入一个中间变量b,而不是仅仅使用hashChannel &lt;- md5.Sum(buffer.Bytes())[:]吗?
  • @boramalper 切片表达式的规范声明“如果切片的操作数是一个数组,它必须是可寻址的。”。在这种情况下,这意味着一个 数组变量 或一个指向数组的 指针间接。我无法准确回答他们做出这个选择的原因。
【解决方案2】:

对数组进行切片。例如,

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]

【讨论】:

    猜你喜欢
    • 2011-10-15
    • 1970-01-01
    • 2014-09-01
    • 2011-06-08
    • 2012-01-10
    • 2014-02-20
    • 2017-12-09
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多