0

Say I have a some code like this:

type SomeType [16]byte

func foo(bar []byte) {
  ...
}

How can I copy bar in foo() to a SomeType instance?

markzz
  • 1,185
  • 11
  • 23

2 Answers2

3

As of Go 1.17 you can convert a slice to an array pointer so long as the slice is at least large enough to fill the declared array. This would only meet your needs if you expect bar to be at least 16 bytes.

package main

import "fmt"

type SomeType [16]byte

func foo(bar []byte) SomeType {
    return *(*SomeType)(bar)
}

func main() {
    fmt.Println(foo([]byte("A 16 byte slice!")))                   // works
    fmt.Println(foo([]byte("A 16 byte slice and then some more"))) // works but you only access the first 16 bytes
    fmt.Println(foo([]byte("too short")))                          // panics because the underlying array is too short
}
Bracken
  • 989
  • 8
  • 21
2

Use copy, but convert the array to a slice first:

type SomeType [16]byte

func foo(bar []byte) SomeType {
    var ret SomeType
    copy(ret[:], bar)
    return ret
}

func main() {
    r := foo([]byte{1, 2, 3})
    fmt.Println(r)
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59