Evan Carroll
Evan Carroll

Reputation: 1

Cannot call non-const fn `<Foo as Default>::default` in constants

I'm trying to create a global instance that I can borrow a reference too,

const GLOBAL_FOO: &Foo = &Foo::default();

impl<'a> Default for Bar<'a> {
    fn default() -> Self {
        Self { foo: GLOBAL_FOO }
    }
}

But when I do this, I get an error,

error[E0015]: cannot call non-const fn `<Foo as Default>::default` in constants
 --> src/main.rs:8:27
  |
8 | const GLOBAL_FOO: &Foo = &Foo::default();
  |                           ^^^^^^^^^^^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants

For more information about this error, try `rustc --explain E0015`.

How can I work around calling default in a const to accomplish this?

Upvotes: 3

Views: 5730

Answers (1)

Evan Carroll
Evan Carroll

Reputation: 1

The problem here is that the Default trait declares default() without const. Thus it's not a constant function. This means that currently, as of Rust 1.6, if you need a constant Default you'll have to implement it yourself,

impl Foo {
  const fn new_const_default() -> Self {
    Self { ... }
  }
}

Note, to eliminate redundancy, you can implement Default on top of your new default(),

impl Default for Foo {
    fn default() -> Self { Self::new_const_default() }
}

Upvotes: 2

Related Questions