如何將一種型別轉換為位元組陣列
這是作業示例
// You can edit this code!
// Click here and start typing.
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 語言中定義
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.Compare
Go build failed.
錯誤是正確的,只是比較不匹配。現在我應該如何將簽名型別轉換為位元組陣列
uj5u.com熱心網友回復:
由于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..!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444022.html
