Home >Backend Development >Golang >How do you convert a fixed-size array to a variable-sized slice in Go?

How do you convert a fixed-size array to a variable-sized slice in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 21:37:02355browse

How do you convert a fixed-size array to a variable-sized slice in Go?

Converting Fixed Size Array to Variable Sized Array in Go

When working with arrays and slices in Go, it's essential to understand their differences. Arrays are fixed-size data structures, while slices are variable-sized and more flexible.

In the given example, you're trying to convert a fixed-size array of 32 bytes ([32]byte) into a variable-sized slice ([]byte). However, attempting this directly with b := []byte(a) will result in a compilation error.

Solution

To successfully convert a fixed-size array into a variable-sized slice, follow this syntax:

b := a[:]

By using the syntax a[:], you create a slice that references the underlying array elements. This is known as "slicing" an array. The resulting slice b will have the same elements as the original array a but will behave like a variable-sized slice, allowing you to modify its length dynamically.

Example

package main

import (
    "fmt"
)

func main() {
    var a [32]byte
    b := a[:]
    fmt.Println(len(b)) //prints 32, indicates the initial length of b matches array a
    b = b[5:] //slicing the slice b, modifies its length
    fmt.Println(len(b)) //prints 27, indicating the new length of b after slicing
}

The above is the detailed content of How do you convert a fixed-size array to a variable-sized slice in Go?. 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