6

I'm providing a default value for a const generic type but the Rust compiler tells me it "cannot infer the value of const parameter". It seems to ignore the default. Am I using this feature wrong? Is this how it is supposed to work? Then why use defaults at all? I use nightly 1.60.

const DEFAULT_N: usize = 73;

struct Foo<const N: usize = DEFAULT_N>;

impl<const N: usize> Foo<N> {
    fn new() -> Self {
        println!("N is: {}", N);
        Self
    }
}

fn main() {
    Foo::new();
}
3
  • I never used this feature, but should't you specify the default value also in the impl declaration ? Commented Feb 23, 2022 at 9:51
  • 1
    @Peterrabbit No, specifying a default in an impl block is an error. (error: defaults for const parameters are only allowed in struct, enum, type, or trait definitions) Commented Feb 23, 2022 at 9:58
  • @cdhowie Yep, that's what I'm seeing... Commented Feb 23, 2022 at 10:01

1 Answer 1

4

I got it working like this

const DEFAULT_N: usize = 73;

struct Foo<const N: usize = DEFAULT_N>;

impl<const N: usize> Foo<N> {
    fn new() -> Self {
        println!("N is: {}", N);
        Self
    }
}

fn main() {
    let f:Foo = Foo::new(); // just added the asked type annotation here
}

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting, so it looks like currently defaults only apply when naming the type itself and not using a member of it. The N on the right is inferred from the N on the left, and the N on the left is inferred to be the default. This seems like it could be a bug and might be worth opening a github issue to see what the devs think.
Image
Has anyone opened an issue on github in regards to this? If not, I can.
@JonathanWoollett-light Sounds like no-one did. Did you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.