How do you convert a slice into an array?

You have allocated four bytes inside that struct and want to assign a value to that four byte section. There is no conceptual way to do that without copying.

Look at the copy built-in for how to do that.


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

Tags:

Go