-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Closed as not planned
Description
Proposal Details
I propose a small, trivial addition to the slices package.
// Safely converts a potentially nil pointer into a slice without copying the underlying data.
// If input is nil the result is the nil slice
// Otherwise the result is a slice with length 1
func FromPointer[T any](t *T) []T {
if t == nil {
return nil
}
// Safety: T and [1]T have the same memory layout.
return (*[1]T)(unsafe.Pointer(t))[:]
}This is inspired by Rust's Option::as_slice which has the main advantage of not doing any copying of the underlying data which can come in handy, especially when dealing with large types such as buffers.
bep, apparentlymart, jakebailey and zigo101sten4eg, DeedleFake and tmthrgdbepbep