Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading