Home >Backend Development >Golang >How to Convert Go Arrays to Slices for Function Passing?
When working with Go, you may encounter situations where you need to convert arrays to slices for further processing. Arrays are fixed-size collections of elements, while slices are dynamic and can grow or shrink as needed.
Consider the following scenario: you have a function that returns an array of bytes:
func Foo() [32]byte {...}
You want to pass the result of this function to another function that expects a slice of bytes:
func Bar(b []byte) { ... }
Simply assigning the array to the slice, like so:
d := Foo() Bar(d)
will result in a compilation error due to type mismatch. To convert the array to a slice, you can use the [:] syntax to create a slice header that points to the underlying array:
func main() { x := Foo() Bar(x[:]) }
This operation does not create a copy of the underlying data; instead, it creates a slice header that references the same memory location as the array.
Here's a complete example that demonstrates the conversion and passing of the array to the Bar function:
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[:]) }
The above is the detailed content of How to Convert Go Arrays to Slices for Function Passing?. For more information, please follow other related articles on the PHP Chinese website!