如何將一種類型轉(zhuǎn)換為字節(jié)數(shù)組這是工作示例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 語(yǔ)言中定義type Signature [5]byte所以這是預(yù)期的var bytes0to64 Signature = SignatureFromBytes([]byte("Here is a string..........")) fmt.Println(reflect.TypeOf(bytes0to64))它只是將類型輸出到main.Signature這是正確的,現(xiàn)在我想從中獲取字節(jié)數(shù)組以進(jìn)行下一級(jí)處理并得到編譯錯(cuò)誤./prog.go:23:29: cannot use bytes0to64 (type Signature) as type []byte in argument to bytes.CompareGo build failed.錯(cuò)誤是正確的,只是比較時(shí)不匹配?,F(xiàn)在我應(yīng)該如何將簽名類型轉(zhuǎn)換為字節(jié)數(shù)組
1 回答

紅顏莎娜
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
由于Signature是一個(gè)字節(jié)數(shù)組,您可以簡(jiǎn)單地將其切片:
bytes0to64[:]
這將導(dǎo)致值為[]byte。
測(cè)試它:
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 關(guān)注
- 144 瀏覽
添加回答
舉報(bào)
0/150
提交
取消