When dealing with something like a sha256
hash which has a known length of 32 bytes– is it more idiomatic to work with []byte
slices or [32]byte
arrays?
I'm a bit new to go– but intuitively it feels like while working with a [32]byte
array to store a hash is nice and explicit, it's actually quite cumbersome to manipulate and requires all sorts of strange things like copying the array into a new buffer slice to manipulate as []byte
.
Looking at the Go standard library, it looks like arrays are often used for something like a hash of known length. e.g sha256.Sum256 returns a [sha256.Size]byte
where sha256.Size
is 32. Or looking at the digest
struct that implements the hash.Hash
interface in sha256
it contains [chunk]byte
where chunk
is 64, the sha256 blocksize.
I think it is typical to use arrays to avoid unnecessary memory allocation. To take advantage of algorithms that operate on slices of a variable length you can convert the array to a slice without copying with x[:]
.
package main
import (
"crypto/sha256"
"fmt"
)
type myHash struct {
x [32]byte
}
func print(b []byte) {
fmt.Print(b)
}
func main() {
b := []byte("Hello world!")
h := myHash{x: sha256.Sum256(b)}
print(h.x[:])
}
Slices are first class in Go and seem to be the preferred way based on their compared usage to arrays in the standard library.
Converting an array to a slice is straitforward as well:
package main
import (
"fmt"
)
func main() {
array := [5]int{1, 2, 3, 4, 5}
slice := array[:]
fmt.Println("Hello, playground", array, slice)
}