Skip to content

Slice with size known at compile time should be coerced to array #1772

Closed
@est31

Description

@est31

You should be able to write stuff like:

fn do_sum(a: [u8; 2]) -> u8 {
    a[0] + a[1]
}

fn main() {
    let arr = [1, 2, 3, 4, 5, 6, 7, 8];
    println!("The sum is {}", do_sum(arr[0..2]));
}

If subslice notation ([] with a range inside) is used on a slice or array with the borders known at compile time, it should be coerced to an array.

There is a stackoverflow thread with a list of workarounds, and someone has even done a crate for the problem, but it should be solved inside the language, as it doesn't really feel natural.

Also, if one end is unspecified, it should allow for values only known at runtime for the specified end, and infer the unspecified end from the type of the function. Example code:

fn do_sum(a: [u8; 2]) -> u8 {
    a[0] + a[1]
}

fn main() {
    let arr = [1, 2, 3, 4, 5, 6, 7, 8];
    for i in 0 .. 8 {
        println!("The sum is {}", do_sum(arr[i..]));
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions