[英]How to convert type to byte array golang
如何將一種類型轉換為字節數組
這是工作示例
package main
import (
"bytes"
"fmt"
"reflect"
)
type Signature [5]byte
const (
/// 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 lang 中定義
type Signature [5]byte
所以這是預期的
var bytes0to64 Signature = SignatureFromBytes([]byte("Here is a string.........."))
fmt.Println(reflect.TypeOf(bytes0to64))
它只是 output 的類型
main.Signature
這是正確的,現在我想從中獲取字節數組以進行下一級處理並得到編譯錯誤
./prog.go:23:29: cannot use bytes0to64 (type Signature) as type []byte in argument to bytes.Compare
Go build failed.
錯誤是正確的,只是比較時不匹配。 現在我應該如何將簽名類型轉換為字節數組
由於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..!")
}
這將是 output(在Go 游樂場上試試):
!..Slice are not equal..!
!..Slices are equal..!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.