Skip to content

[ER] NonZero const generic constructor #73121

Open
@leonardo-m

Description

@leonardo-m

It could be nice to have std::iter::Step for the NonZeroX numbers, so in this code instead of having about 1000 unwrap:

fn main() {
    use std::num::NonZeroUsize;
    let nz = |x| NonZeroUsize::new(x).unwrap();
    for i in 1 .. 1_000 {
        println!("{:?}", nz(i));
    }
}

You only need two:

fn main() {
    use std::num::NonZeroUsize;
    let nz = |x| NonZeroUsize::new(x).unwrap();
    for i in nz(1) .. nz(1_000) {
        println!("{:?}", i);
    }
}

If also a const-generics-based constructor is added to stdlib then the number of run-time unwraps goes to zero (the two panics become compile-time):

fn main() {
    use std::num::nonzero_usize;
    for i in nonzero_usize::<1>() .. nonzero_usize::<1_000>() {
        println!("{:?}", i);
    }
}

A further improvement should come from const generics of arbitrary type (currently not allowed):

fn main() {
    use std::num::nonzero;
    for i in nonzero::<1_usize>() .. nonzero::<1_000>() {
        println!("{:?}", i);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.S-waiting-on-ACPStatus: PR has an ACP and is waiting for the ACP to complete.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions