Golang converts type [N] bytes to [] bytes

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 an explicit conversion, this does not work. I can also store a byte like [16], but at some point I need to convert it, since I am sending it over a TCP connection:

 _, _ = conn.Write(h) 

What is the best way to convert it? Thanks

+8
slice go
source share
2 answers

Cut 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] 
+8
source share

Creating a slice using an array, you can simply 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[:] 
+3
source share

All Articles