I am trying to write an application that reads RPM files. The start of each block has a Magic char of [4]byte
.
Here is my struct
type Lead struct { Magic [4]byte Major, Minor byte Type uint16 Arch uint16 Name string OS uint16 SigType uint16 }
I am trying to do the following:
lead := Lead{} lead.Magic = buffer[0:4]
I am searching online and not sure how to go from a slice to an array (without copying). I can always make the Magic []byte
(or even uint64
), but I was more curious on how would I go from type []byte
to [4]byte
if needed to?
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.
slice is a composite data type and because it is composed of primitive data type (see variables lesson for primitive data types). Syntax to define a slice is pretty similar to that of an array but without specifying the elements count. Hence s is a slice.
Slices are pointers to arrays, with the length of the segment, and its capacity. They behave as pointers, and assigning their value to another slice, will assign the memory address.
The built in method copy will only copy a slice to a slice NOT a slice to an array.
You must trick copy into thinking the array is a slice
copy(varLead.Magic[:], someSlice[0:4])
Or use a for loop to do the copy:
for index, b := range someSlice { varLead.Magic[index] = b }
Or do as zupa has done using literals. I have added onto their working example.
Go Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With