Home > Backend Development > Golang > How to Convert Go Arrays to Slices for Function Passing?

How to Convert Go Arrays to Slices for Function Passing?

Barbara Streisand
Release: 2024-12-12 18:28:22
Original
460 people have browsed it

How to Convert Go Arrays to Slices for Function Passing?

Converting Arrays to Slices in Go

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 {...}
Copy after login

You want to pass the result of this function to another function that expects a slice of bytes:

func Bar(b []byte) { ... }
Copy after login

Simply assigning the array to the slice, like so:

d := Foo()
Bar(d)
Copy after login

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[:])
}
Copy after login

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[:])
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template