reflect.SliceHeader and reflect.StringHeader are clumsy to use because their Data fields have type uintptr instead of unsafe.Pointer.
This proposal is to add types unsafe.Slice and unsafe.String as replacements. They would be declared just like their package reflect analogs, except with unsafe.Pointer-typed Data fields:
type Slice struct {
Data Pointer
Len int
Cap int
}
type String struct {
Data Pointer
Len int
}
Additionally, I suggest that for the purposes of type conversion, we treat that string and unsafe.String have the same underlying type, and also []T and unsafe.Slice. For example, these would be valid:
func makestring(p *byte, n int) string {
// Direct conversion of unsafe.String to string.
return string(unsafe.String{unsafe.Pointer(p), n})
}
func memslice(p *byte, n int) (res []byte) {
// Direct conversion of *[]byte to *unsafe.Slice, without using unsafe.Pointer.
s := (*unsafe.Slice)(&res)
s.Data = unsafe.Pointer(p)
s.Len = n
s.Cap = n
return
}
While the same results can be achieved using unsafe.Pointer conversions, by using direct conversions the compiler can provide a little extra type safety.
reflect.SliceHeaderandreflect.StringHeaderare clumsy to use because theirDatafields have typeuintptrinstead ofunsafe.Pointer.This proposal is to add types
unsafe.Sliceandunsafe.Stringas replacements. They would be declared just like their package reflect analogs, except withunsafe.Pointer-typedDatafields:Additionally, I suggest that for the purposes of type conversion, we treat that
stringandunsafe.Stringhave the same underlying type, and also[]Tandunsafe.Slice. For example, these would be valid:While the same results can be achieved using
unsafe.Pointerconversions, by using direct conversions the compiler can provide a little extra type safety.