英文:
Golang: convert custom type (alias to [32]byte) to string
问题
这与GOLANG语言有关。我找不到如何将一个自定义类型的值转换为字符串表示:
type Hash [32]byte
将该哈希值转换为字符串表示:
myHash := CreateHash("这是一个要进行哈希的示例文本")
fmt.Printf("这是哈希值:%s", string(myHash))
我得到的错误如下:
无法将myHash(类型为Hash的变量)转换为字符串
编译器错误(InvalidConversion)
虽然我可以使用[32]bytes,但我真的想知道如何在GO中做到这一点;我已经搜索了一段时间,但没有找到解决这个确切情况的方法。
提前感谢!
英文:
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!
答案1
得分: 3
Go语言不支持将字节数组转换为字符串,但是支持将字节切片转换为字符串。通过对数组进行切片来修复:
fmt.Printf("This is the hash: %s", string(myHash[:]))
你可以省略转换,因为%s
占位符支持字节切片:
fmt.Printf("This is the hash: %s", myHash[:])
如果哈希值包含的是二进制数据而不是可打印字符,则可以考虑使用%x
占位符打印哈希值的十六进制编码:
fmt.Printf("This is the hash: %x", myHash[:])
英文:
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[:])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论