如何将类型转换为字节数组golang

How to convert type to byte array golang

如何将一种类型转换为字节数组

这是工作示例

// 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))

只是把Type输出到

main.Signature

这是正确的,现在我想从中获取字节数组进行下一级处理并得到编译错误

./prog.go:23:29: cannot use bytes0to64 (type Signature) as type []byte in argument to bytes.Compare

Go build failed.

错误是对的,只是比较不匹配。现在我应该如何将签名类型转换为字节数组

因为Signature是一个字节数组,你可以简单地slice它:

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..!