6

I have this code:

func my_function(hash string) [16]byte {
    b, _ := hex.DecodeString(hash)
    return b   // Compile error: fails since [16]byte != []byte
}

b will be of type []byte. I know that hash is of length 32. How can I make my code above work? Ie. can I somehow cast from a general-length byte array to a fixed-length byte array? I am not interested in allocating 16 new bytes and copying the data over.

Ztyx
  • 14,100
  • 15
  • 78
  • 114
  • As in copying a slice to an array? http://stackoverflow.com/a/21399657/6309 – VonC Jan 02 '15 at 19:37
  • No. I prefer to not copy. Added that to question. – Ztyx Jan 02 '15 at 19:42
  • 2
    Not convertible without `unsafe`. The slice header itself is 24 bytes on amd64 and is copied to the stack when `hex.DecodeString` returns, and hashing itself is going to be far, far more expensive than copying a 16-byte result; I'd pick your battles and not worry too much about this one. – twotwotwo Jan 02 '15 at 20:03

1 Answers1

13

There is no direct method to convert a slice to an array. You can however do a copy.

var ret [16]byte
copy(ret[:], b)

The standard library uses []byte and if you insist on using something else you will just have a lot more typing to do. I wrote a program using arrays for my md5 values and regretted it.

Stephen Weinberg
  • 51,320
  • 14
  • 134
  • 113
  • 1
    Notice that you can usually make sure that data you receive ends up in an array variable by slicing the array variable (e.g. `foo[:]`). This is useful when you want to actually use arrays for performance reasons but you still want to `Read()` and `Write()` into them. – fuz Jan 03 '15 at 01:42