Home > Backend Development > Golang > How to Convert a Go Slice to an Array?

How to Convert a Go Slice to an Array?

Linda Hamilton
Release: 2024-12-11 12:43:11
Original
478 people have browsed it

How to Convert a Go Slice to an Array?

Converting Slice to Array in Go

In Go, attempting to assign a slice to an array directly will result in a compilation error. This question explores how to convert slices of specific lengths into arrays.

Problem Statement

Consider a struct defining a lead block with a Magic field consisting of an array of 4 bytes:

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

The task is to assign a slice of 4 bytes to the Magic field using the following syntax:

lead := Lead{}
lead.Magic = buffer[0:4] // Attempt to assign slice to array
Copy after login

Solution

To convert a slice of a specified length into an array, Go provides the following methods:

Using copy() with Array Subslice

The built-in copy function can be tricked into copying a slice to an array by treating the array as a slice:

copy(varLead.Magic[:], someSlice[0:4])
Copy after login

Using For Loop

Iterate over the slice elements and assign them to the array elements:

for index, b := range someSlice {
    varLead.Magic[index] = b
}
Copy after login

Using Array Literals

An alternative approach is to use array literals directly:

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

lead := Lead{Magic: [4]byte{0x12, 0x34, 0x56, 0x78}}
Copy after login

The above is the detailed content of How to Convert a Go Slice to an Array?. 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