Skip to content

proposal: slices: add FromPointer function #76109

@davidgauch

Description

@davidgauch

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions