Home >Backend Development >Golang >How Can I Convert a Go Slice to an Array Without Copying?

How Can I Convert a Go Slice to an Array Without Copying?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 06:14:12795browse

How Can I Convert a Go Slice to an Array Without Copying?

Converting Slices to Arrays

In Go, converting a slice to an array without copying can be achieved by using a trick or a for loop.

To use the trick, pass the array as a slice to the copy function:

type Lead struct {
  Magic        [4]byte
  Major, Minor byte
  Type         uint16
  Arch         uint16
  Name         string
  OS           uint16
  SigType      uint16
}

lead := Lead{}
copy(lead.Magic[:], buffer[0:4])

Alternatively, a for loop can be used:

for index, b := range buffer[0:4] {
    lead.Magic[index] = b
}

Using literals, a slice can be directly converted to an array:

type Lead struct {
  Magic        [4]byte
  Major, Minor byte
  Type         uint16
  Arch         uint16
  Name         string
  OS           uint16
  SigType      uint16
}

lead := Lead{
  Magic: [4]byte{'h', 'e', 'l', 'l'},
  ...
}

The above is the detailed content of How Can I Convert a Go Slice to an Array Without Copying?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn