Golang: convert custom type (alias to [32]byte) to string


This is related to GOLANG language. I can’t find out how to convert a value that is of a custom type:

type Hash [32]byte

into a string representation of that hash:

myHash := CreateHash("This is an example text to be hashed")
fmt.Printf("This is the hash: %s", string(myHash))

The error I’m getting is the following:

cannot convert myHash (variable of type Hash) to string

While I’m ok using just [32]bytes, I’d really like to know how to do this in GO; I have been for a while searching and couldn’t find a solution this exact case.

Thanks in advance!


Go does not support conversion from byte array to string, but Go does support conversion from a byte slice to a string. Fix by slicing the array:

fmt.Printf("This is the hash: %s", string(myHash[:]))

You can omit the conversion because the %s verb supports byte slices:

fmt.Printf("This is the hash: %s", myHash[:])

If the hash contains binary data instead of printable characters, then consider printing the hexadecimal encoding of the hash with the %x verb:

fmt.Printf("This is the hash: %x", myHash[:])

Answered By – Zombo

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.