0

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 compiler(InvalidConversion)

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!

Eduardo G.R.
  • 377
  • 3
  • 18
  • 3
    The statement `type Hash [32]byte` declares a new type, not an [alias](https://go.dev/ref/spec#Alias_declarations). –  Mar 16 '22 at 18:52

1 Answers1

3

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[:])