相当于 C++ 中的 constexpr? [英] Equivalent of constexpr from C++?

查看:47
本文介绍了相当于 C++ 中的 constexpr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看此代码:

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

rustc 输出

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

但是 something_const 不是动态的,因为它在编译时是已知的.

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

它在 Rust 中是否等同于 C++ constexpr 机制?

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

推荐答案

constexpr 在 C++ 中可以用于 2 种不同的情况:

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

  • 限定一个常量,并表示该常量必须在编译时可用
  • 限定一个函数,并表示该函数必须可用于编译时评估

Rust 支持两者,尽管方式有限:

Rust supports both, albeit in a limited fashion:

  • 你可以使用const来声明一个常量,而不是let来声明它是真正的常量
  • 你可以使用 const 来限定一个函数,声明它可以在编译时被评估.并非所有函数都可以const.
  • you can use const to declare a constant, instead of let, to declare that it is truly constant
  • you can use const to qualify a function, to declare that it can be evaluated at compile-time. Not all functions can be made const yet.

在您的情况下,您需要第一个用法:

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));
}

请注意,与 let 不同的是,必须使用其类型注释常量.

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

另外,编译器会抱怨命名;常量使用 ALL_CAPS.

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

这篇关于相当于 C++ 中的 constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆