snippetgoCritical
Convert array to slice in Go
Viewed 0 times
arrayconvertslice
Problem
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
I have a function that I call from an external lib that returns an array
I then need to pass that result to a different function for further processing.
Unforunately, if I try to call
I get
Doing
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).
[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 []byteDoing
[]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).
Solution
This should work:
And it doesn't create a copy of the underlying buffer
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
Code Snippets
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[:])
}Context
Stack Overflow Q#28886616, score: 154
Revisions (0)
No revisions yet.