在Go中,如何将myByte转换为[]字节? [英] In Go, how do I convert []myByte to []byte?

查看:112
本文介绍了在Go中,如何将myByte转换为[]字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了类型myByte byte ,因为我想在逻辑上区分不同类型的字节。

我可以用 byte(myByte(1))

但我无法找到转换或转换切片: [] byte([] myByte {1})失败。



这样的事情可能吗?这些位在内存中是相同的(右?),所以应该有某种方法,不需要逐字节复制到一个新对象中。



例如,没有这个作品: http://play.golang.org/p/WPhD3KufR8










$ func main(){
a: = [] myByte {1}

fmt.Print(byte(myByte(1)))// Works OK

fmt.Print([] byte([] myByte {1}))//失败:无法将[] myByte文字(类型[] myByte)转换为类型[]字节

//不能使用(type [] myByte)作为类型[]字节在函数参数
// fmt.Print(bytes.Equal(a,b))

//不能将一个(type [] myByte)转换为type [] byte
// [] byte(a)

// panic:interface conversion:interface is [] main.myByte,not [] uint8
// abyte:=(interface {}(a ))。([] byte)
}


解决方案

你不能将你自己的myByte的片转换为as

但是你可以拥有自己的字节片类型,它可以转换为
a字节片:

 包主
$ b $导入fmt

类型myBytes []字节

func main(){
var bs [] byte
bs = [] byte(myBytes {1,2,3})
fmt.Println(bs)
}

根据您的问题,这可能是一个不错的解决方案。
(您无法区分myBytes和字节
中的一个字节,但您的切片是类型安全的。)


I have a type myByte byte that I use because I want to logically differentiate different kinds of bytes.

I can convert easily with byte(myByte(1)),

but I can't find away to cast or convert an slice: []byte([]myByte{1}) fails.

Is such a thing possible? The bits are the same in memory (right?) so there should be some way, short of copying byte by byte into a new object..

For example, none of this works: http://play.golang.org/p/WPhD3KufR8

package main

type myByte byte

func main() {
a := []myByte{1}

fmt.Print(byte(myByte(1))) // Works OK

fmt.Print([]byte([]myByte{1})) // Fails: cannot convert []myByte literal (type []myByte) to type []byte

// cannot use a (type []myByte) as type []byte in function argument
// fmt.Print(bytes.Equal(a, b))

// cannot convert a (type []myByte) to type []byte
// []byte(a)

// panic: interface conversion: interface is []main.myByte, not []uint8
// abyte := (interface{}(a)).([]byte)
}

解决方案

You cannot convert slices of your own myByte to a slice of byte.

But you can have your own byte-slice type which can be cast to a byte slice:

package main

import "fmt"

type myBytes []byte

func main() {
     var bs []byte
     bs = []byte(myBytes{1, 2, 3})
     fmt.Println(bs)
}

Depending on your problem this might be a nice solution. (You cannot distinguish a byte from myBytes from a byte, but your slice is typesafe.)

这篇关于在Go中,如何将myByte转换为[]字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆