Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert fixed size array to variable sized array in Go

I'm trying to convert a fixed size array [32]byte to variable sized array (slice) []byte:

package main

import (
        "fmt"
)

func main() {
        var a [32]byte
        b := []byte(a)
        fmt.Println(" %x", b)
}

but the compiler throws the error:

./test.go:9: cannot convert a (type [32]byte) to type []byte

How should I convert it?

like image 410
Stein Avatar asked Jan 20 '15 13:01

Stein


2 Answers

Use b := a[:] to get the slice over the array you have. Also see this blog post for more information about arrays and slices.

like image 76
Makpoc Avatar answered Nov 13 '22 18:11

Makpoc


There are no variable-sized arrays in Go, only slices. If you want to get a slice of the whole array, do this:

b := a[:] // Same as b := a[0:len(a)]
like image 40
Ainar-G Avatar answered Nov 13 '22 18:11

Ainar-G