Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang convert type [N]byte to []byte [duplicate]

Tags:

slice

go

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

like image 269
Michael Avatar asked Mar 31 '15 07:03

Michael


2 Answers

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]
like image 159
peterSO Avatar answered Oct 17 '22 17:10

peterSO


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[:]
like image 7
ANisus Avatar answered Oct 17 '22 17:10

ANisus