Home >Backend Development >Golang >How do you convert a fixed-size array to a variable-sized slice in Go?
When working with arrays and slices in Go, it's essential to understand their differences. Arrays are fixed-size data structures, while slices are variable-sized and more flexible.
In the given example, you're trying to convert a fixed-size array of 32 bytes ([32]byte) into a variable-sized slice ([]byte). However, attempting this directly with b := []byte(a) will result in a compilation error.
To successfully convert a fixed-size array into a variable-sized slice, follow this syntax:
b := a[:]
By using the syntax a[:], you create a slice that references the underlying array elements. This is known as "slicing" an array. The resulting slice b will have the same elements as the original array a but will behave like a variable-sized slice, allowing you to modify its length dynamically.
package main import ( "fmt" ) func main() { var a [32]byte b := a[:] fmt.Println(len(b)) //prints 32, indicates the initial length of b matches array a b = b[5:] //slicing the slice b, modifies its length fmt.Println(len(b)) //prints 27, indicating the new length of b after slicing }
The above is the detailed content of How do you convert a fixed-size array to a variable-sized slice in Go?. For more information, please follow other related articles on the PHP Chinese website!