28

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?

2 Answers 2

43

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

Sign up to request clarification or add additional context in comments.

Comments

20

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)]

1 Comment

Note that slices behave a bit like variable-sized arrays in that, if you keep using append on a slice, it will grow by reallocation when necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.