Skip to content

ACP: Add try_from_slice constructor to core::array. #496

Closed
@bjoernager

Description

@bjoernager

Proposal

Problem statement

In Rust, you can convert a slice &[T] to an array [T; N] using <[T; N] as TryFrom<&[T]>>::try_from. The main issue with this is that it depends on a trait function, and trait functions are not allowed in constant expressions (e.g. const fn).

I propose adding a try_from_slice function to the core::array module for this scenario. The module in question already defines other constructors such as from_fn and from_ref.

Solution sketch

The following function should be added to the standard library:

// core::array

pub const fn try_from_slice<T, const N: usize>(slice: &[T]) -> Result<[T; N], TryFromSliceError>
where
    T: Copy;

Alternatives

The main alternative to adding this feature (with regard to const) would be to allow trait functions in constant expressions. This is already covered by const_trait_impl.

I still do believe adding this function can improve clarity in some code. Other areas of the standard library already define similar patterns, e.g. String implements Into<Box<str>> whilst also defining the into_boxed_str destructor.

Links and related work

Initial, unstable implementation: #133439

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions