Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a slice into an array?

Tags:

go

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?

like image 815
ekaqu Avatar asked Sep 29 '13 02:09

ekaqu


People also ask

Is a slice an array?

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.

What is the difference between a slice and an 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.

What is a slice data type?

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.

Is slice a pointer Golang?

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.


1 Answers

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

like image 141
twinj Avatar answered Oct 05 '22 02:10

twinj