Two const wishes

In the stdlib two of the things that most I'd like usable in const contexts are array::map and try_from:

#![feature(array_map)]

use std::num::NonZeroU32;
use std::convert::TryFrom;

const N: u32 = 7;

const NZ_PRIMES: [NonZeroU32; usize::try_from(N).unwrap()] =
    [2, 3, 5, 7, 11, 13, 17]
    .map(|f| NonZeroU32::new(f).unwrap());

fn main() {}

Both of the use cases involve traits (FnMut and TryFrom), so a precondition for something like this would be having some form of const trait methods.

We don’t even have something like const fn pointers yet; I guess the only way to currently provide anthing like functionality like array::map (e.g. through a crate) is with macros.

3 Likes

Issue 67792 is the tracking issue for exploration into the impl const Trait feature.

2 Likes

Tbh, the main thing I want from const is array slicing. I can generally work around the lack of traits but the only way to simulate slicing is a convoluted abuse of match patterns (if not slicing from zero).

Nice compile time errors would be a close second.

Speaking of which, I was wondering what arguments there are against having trait method implementations become optionally const at implementation time:

trait Foo {
    fn bar(&self) -> usize;
}

impl Foo for str {
    // Given the same string, this will always return the same value
    const fn bar(&self) -> usize {
        self.len()
    }
}

Need to mention this here since I've even seen people try to use const as a way to enforce pureness in macros:

AFAIK, const only means compile time executable, there are no guarantees that it doesn't support side-effects in the future that invalidate statements like this. (I mean, the implementation at hand will still be satisfying this statement, instead I'm referring to that what you write here isn't implied or required by const.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.