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
Release: 2024-12-08 06:14:12
Original
787 people have browsed it

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])
Copy after login

Alternatively, a for loop can be used:

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

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'},
  ...
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template