如何将一种类型转换为字节数组这是工作示例package mainimport ( "bytes" "fmt" "reflect")type Signature [5]byteconst ( /// Number of bytes in a signature. SignatureLength = 5)func main() { var bytes0to64 Signature = SignatureFromBytes([]byte("Here is a string..........")) fmt.Println(reflect.TypeOf(bytes0to64)) res := bytes.Compare([]byte("Test"), bytes0to64) if res == 0 { fmt.Println("!..Slices are equal..!") } else { fmt.Println("!..Slice are not equal..!") }}func SignatureFromBytes(in []byte) (out Signature) { byteCount := len(in) if byteCount == 0 { return } max := SignatureLength if byteCount < max { max = byteCount } copy(out[:], in[0:max]) return}在 Go 语言中定义type Signature [5]byte所以这是预期的var bytes0to64 Signature = SignatureFromBytes([]byte("Here is a string..........")) fmt.Println(reflect.TypeOf(bytes0to64))它只是将类型输出到main.Signature这是正确的,现在我想从中获取字节数组以进行下一级处理并得到编译错误./prog.go:23:29: cannot use bytes0to64 (type Signature) as type []byte in argument to bytes.CompareGo build failed.错误是正确的,只是比较时不匹配。现在我应该如何将签名类型转换为字节数组
1 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
由于Signature是一个字节数组,您可以简单地将其切片:
bytes0to64[:]
这将导致值为[]byte。
测试它:
res := bytes.Compare([]byte("Test"), bytes0to64[:])
if res == 0 {
fmt.Println("!..Slices are equal..!")
} else {
fmt.Println("!..Slice are not equal..!")
}
res = bytes.Compare([]byte{72, 101, 114, 101, 32}, bytes0to64[:])
if res == 0 {
fmt.Println("!..Slices are equal..!")
} else {
fmt.Println("!..Slice are not equal..!")
}
这将输出(在Go Playground上尝试):
!..Slice are not equal..!
!..Slices are equal..!
- 1 回答
- 0 关注
- 70 浏览
添加回答
举报
0/150
提交
取消