在Go中将数组转换为切片 [英] Convert array to slice in Go

查看:219
本文介绍了在Go中将数组转换为切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来好像是一个相当普遍的事情,并且跨网站有很多例子,但我似乎无法找到一个如何将 [32]字节 [] byte



我有一个函数可以从外部库调用,

  func Foo()[32] byte {...} 

然后我需要将该结果传递给另一个函数以供进一步处理。

  func Bar(b [] byte){...} 

不幸的是,if我尝试打电话给

  d:= Foo()
Bar(d)


$ b我得到

 不能转换d (type [32] byte)to type [] byte 

  []字节(d)

并不好。我该如何做到这一点,尤其是在不创建数据副本的情况下(当我所做的所有事情都传递给他人时,似乎很难复制这些数据)。


$ b

  func Foo()[32] byte {
return字节{'0','1','2','3','4','5','6','7','8','9','a',' b,c,d,e,f,0,1,2,3,4,5,6,7, ,'8','9','a','b','c','d','e','f'}
}

func Bar(b [] byte){
fmt.Println(string(b))
}

func main(){
x:= Foo()
Bar (x [:])
}

并不会创建副本底层缓冲区


This seems like it would be a fairly common thing and abundant examples across the interwebs, but I can't seem to find an example of how to convert an [32]byte to []byte.

I have a function that I call from an external lib that returns an array

func Foo() [32]byte {...}

I then need to pass that result to a different function for further processing.

func Bar(b []byte) { ... }

Unforunately, if I try to call

d := Foo()
Bar(d)

I get

cannot convert d (type [32]byte) to type []byte

Doing

[]byte(d)

isn't much better. How do I do this, especially without creating a copy of the data (seems silly to copy this data when all I'm doing is passing it along).

解决方案

This should work:

func Foo() [32]byte {
    return [32]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
}

func Bar(b []byte) {
    fmt.Println(string(b))
}

func main() {
    x := Foo()
    Bar(x[:])
}

And it doesn't create a copy of the underlying buffer

这篇关于在Go中将数组转换为切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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