2015-03-31 17 views
8

ho questo codice:Golang convertire tipo byte [N] a [] byte

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

E ottengo questo errore:

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

Anche senza la conversione esplicita questo non funziona. Posso mantenere il tipo [16] Byte pure, ma ad un certo punto ho bisogno di convertirlo, come sto inviarlo su una connessione TCP:

_, _ = conn.Write(h) 

Qual è il metodo migliore per convertirlo? Grazie

+4

'[:]' converte una matrice a una fetta – Volker

risposta

8

Slice matrice. Ad esempio,

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) 
} 

uscita:

[212 29 140 217 143 0 178 4 233 128 9 152 236 248 66 126] 
3

Creazione di una fetta utilizzando una matrice si può solo fare un simple slice expression:

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

o nel vostro caso:

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

ERRORE: 'hashChannel <- md5.Sum (buffer.Bytes()) []:' errore è 'operazione non valida md5.Sum (buffer.Bytes()) [:] (fetta di valore non inviolabile)' – peterSO

+0

peterSo: Ah, sì. Perdonami per quello. Insetto davvero. Corretto – ANisus

+1

@ANisus Sapete perché abbiamo bisogno di introdurre una variabile intermedia 'b' piuttosto che usare' hashChannel <- md5.Sum (buffer.Bytes()) [:] 'per esempio? – boramalper

Problemi correlati