Converting Slice to Array in Go
In Go, attempting to assign a slice to an array directly will result in a compilation error. This question explores how to convert slices of specific lengths into arrays.
Problem Statement
Consider a struct defining a lead block with a Magic field consisting of an array of 4 bytes:
type Lead struct { Magic [4]byte Major, Minor byte Type uint16 Arch uint16 Name string OS uint16 SigType uint16 }
The task is to assign a slice of 4 bytes to the Magic field using the following syntax:
lead := Lead{} lead.Magic = buffer[0:4] // Attempt to assign slice to array
Solution
To convert a slice of a specified length into an array, Go provides the following methods:
Using copy() with Array Subslice
The built-in copy function can be tricked into copying a slice to an array by treating the array as a slice:
copy(varLead.Magic[:], someSlice[0:4])
Using For Loop
Iterate over the slice elements and assign them to the array elements:
for index, b := range someSlice { varLead.Magic[index] = b }
Using Array Literals
An alternative approach is to use array literals directly:
type Lead struct { Magic [4]byte Major, Minor byte Type uint16 Arch uint16 Name string OS uint16 SigType uint16 } lead := Lead{Magic: [4]byte{0x12, 0x34, 0x56, 0x78}}
The above is the detailed content of How to Convert a Go Slice to an Array?. For more information, please follow other related articles on the PHP Chinese website!