go: reflect: permit Value.Bytes (but not SetBytes) on addressable byte arrays
I’m trying to get a []byte of an array via reflect, without allocations.
reflect.Value.Bytes says:
Bytes returns v’s underlying value. It panics if v’s underlying value is not a slice of bytes.
I have an array, not a slice. I can slice it, but reflect.Value.Slice call allocates:
func TestArraySliceAllocs(t *testing.T) {
type T struct {
X [32]byte
}
x := &T{X: [32]byte{1: 1, 2: 2, 3: 3, 4: 4}}
var b []byte
n := int(testing.AllocsPerRun(2000, func() {
v := reflect.ValueOf(x)
b = v.Elem().Field(0).Slice(0, 5).Bytes()
}))
if n != 0 {
t.Errorf("allocs = %d; want 0", n)
}
const want = "\x00\x01\x02\x03\x04"
if string(b) != want {
t.Errorf("got %q; want %q", b, want)
}
}
(fails with 1 alloc, from Slice)
Perhaps reflect.Value.Bytes could also permit getting a []byte of an array of bytes?
Or maybe I’m holding reflect wrong and there’s an alloc-free way to do this already.
/cc @josharian
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 3
- Comments: 23 (22 by maintainers)
Commits related to this issue
- doc: add release note for reflect.Value.{Bytes,Len,Cap} Update #47066 Update #52411 Change-Id: I85139d774c16c9e6d1a2592a5abba58a49338674 Reviewed-on: https://go-review.googlesource.com/c/go/+/408874... — committed to golang/go by randall77 4 years ago
- reflect: allow Value.Bytes on addressable byte arrays Modify Value.Bytes to be callable addressable byte arrays. While related, the behavior of Value.SetBytes was not modified. Fixes #47066 Change-... — committed to salewski/go by dsnet 5 years ago
I see. I think it would be fine to allow
Bytesto work on an addressable array (or pointer to array?).