如何将类型转换为字节数组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 语言中定义


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.


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


ITMISS
浏览 77回答 1
1回答

红颜莎娜

由于Signature是一个字节数组,您可以简单地将其切片:bytes0to64[:]这将导致值为[]byte。测试它:res := bytes.Compare([]byte("Test"), bytes0to64[:])if res == 0 {&nbsp; &nbsp; fmt.Println("!..Slices are equal..!")} else {&nbsp; &nbsp; fmt.Println("!..Slice are not equal..!")}res = bytes.Compare([]byte{72, 101, 114, 101, 32}, bytes0to64[:])if res == 0 {&nbsp; &nbsp; fmt.Println("!..Slices are equal..!")} else {&nbsp; &nbsp; fmt.Println("!..Slice are not equal..!")}这将输出(在Go Playground上尝试):!..Slice are not equal..!!..Slices are equal..!
打开App,查看更多内容
随时随地看视频慕课网APP