繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM