Equivalent of constexpr from C++?

2019-06-16 00:06发布

See this code:

fn main() {
    let something_const = 42;
    fn multiply(nbr: i32) -> i32 {
        nbr * something_const
    }
    println!("{}", multiply(1));
}

rustc outputs that

error[E0434]: can't capture dynamic environment in a fn item; use the || { ... } closure form instead
  --> main.rs:19:15
   |
19 |         nbr * something_const
   |               ^^^^^^^^^^^^^^^

But something_const is not dynamic, because it is known at compile time.

Is it an equivalent in Rust of the C++ constexpr mechanism?

标签: rust
1条回答
beautiful°
2楼-- · 2019-06-16 00:37

constexpr in C++ can be used in 2 different situations:

  • to qualify a constant, and denote that this constant must be available at compile-time
  • to qualify a function, and denote that this function must be available for compile-time evaluation

Rust supports both, albeit in a limited fashion:

  • you can use const to declare a constant, instead of let, to declare that it is truly constant
  • on nightly, you can use const to qualify a function, to declare that it can be evaluated at compile-time

In your situation, you want the first usage:

fn main() {
    const something_const: i32 = 42;
    fn multiply(nbr: i32) -> i32 {
        nbr * something_const
    }
    println!("{}", multiply(1));
}

Note that unlike with let, it is mandatory to annotate the constant with its type.

Also, the compiler will complain about the naming; constants use ALL_CAPS.

查看更多
登录 后发表回答