Home >Backend Development >Golang >How do I convert a slice to a fixed-size array in Go?
Converting Slice to Fixed Size Array in Go
In Go, you may encounter a situation where you need to convert a variable-sized slice into a fixed-size array. However, attempting to assign a slice directly to an array can result in an error.
To effectively convert a slice into a fixed-size array, you can utilize the 'copy' function. This function allows you to copy a specified number of elements from the source slice into the target array.
The code below demonstrates how to use the 'copy' function:
slice := []byte("abcdefgh") var arr [4]byte copy(arr[:], slice[:4]) fmt.Println(arr)
In this example, the 'copy' function copies the first four elements from the 'slice' into the 'arr' array. By providing the slice indices as arguments to 'copy', you can control the number of elements being copied.
Alternatively, as suggested by Aedolon, you can simplify the code by using the following syntax:
copy(arr[:], slice)
This is because 'copy' automatically copies the minimum of the lengths of the source and destination slices.
With these methods, you can effectively convert slices into fixed-size arrays in Go, ensuring that the appropriate number of elements is copied and maintaining type safety.
The above is the detailed content of How do I convert a slice to a fixed-size array in Go?. For more information, please follow other related articles on the PHP Chinese website!