-
Notifications
You must be signed in to change notification settings - Fork 18.3k
Closed
Milestone
Description
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.
josharian, cespare, ericlagergren, n10v, rasky and 48 moretmthrgd, guillaume-000, encendre, dennwc, elichai and 1 more