Home > Article > Backend Development > How do I convert a Go slice to a fixed-size array?
Converting Slices to Fixed Size Arrays
It is common to encounter scenarios where you need to convert a slice into a fixed size array. In Go, slices are dynamic data structures that can grow and shrink, while arrays are fixed size and must be initialized with a specific size.
Consider the following code:
func gen(bricks []Brick) { if len(bricks) == 16 { if check(Sculpture{bricks}) { var b [16]Brick = bricks[0:16]; // Error: Cannot assign slice to array } } }
In this code, we attempt to convert a slice named bricks to a fixed size array b. However, this results in an error because slices and arrays have different types.
Using copy
To convert a slice to a fixed size array, you can use the copy function. The copy function copies elements from one slice or array to another. It takes two arguments: the destination slice or array and the source slice or array.
The following example demonstrates how to use copy to convert a slice to an array:
slice := []byte("abcdefgh") var arr [4]byte copy(arr[:], slice[:4]) fmt.Println(arr)
In this example, the copy function copies the first four bytes of the slice to the arr array. The resulting array will contain the values [97 98 99 100].
Using slice-to-array conversions (Go 1.17 )
In Go versions 1.17 and higher, a new feature was introduced to support slice-to-array conversions. This allows you to directly assign a slice to an array pointer without using the copy function.
The following example demonstrates the use of slice-to-array conversions:
s := make([]byte, 2, 4) s0 := (*[0]byte)(s) // s0 != nil s1 := (*[1]byte)(s[1:]) // &s1[0] == &s[1] s2 := (*[2]byte)(s) // &s2[0] == &s[0] // s4 := (*[4]byte)(s) // panics: len([4]byte) > len(s)
In this example, we create a slice s and then use it to initialize three array pointers: s0, s1, and s2. s0 is a pointer to an array of zero length, s1 is a pointer to an array of one element, and s2 is a pointer to an array of two elements.
Note that this feature is only available for slices that are backed by an underlying array. If the slice is not backed by an array, you will still need to use the copy function to convert it to an array.
The above is the detailed content of How do I convert a Go slice to a fixed-size array?. For more information, please follow other related articles on the PHP Chinese website!