编者注:从 Rust 1.43 开始,这按预期工作。
我有一个类型别名 type CardId = u64;
我想通过 std::u64::MAX
常量将它初始化为它可以拥有的最大数量.得知我无法通过别名执行相同操作时感到很惊讶。
use std::u64;
type CardId = u64;
fn main() {
let this_works = u64::MAX;
let this_doesnt_work = CardId::MAX;
println!("Max amount in integer: {} and {}", this_works, this_doesnt_work);
}
我期望 MAX
常量也可以从类型别名访问。当我将类型更改为 u32 时,这会帮助我,这会导致代码有两点我需要修改,而不仅仅是类型别名的位置。为什么做出这个决定,我是否错过了一些可能使这成为可能的东西?
最佳答案
在 Rust 1.43 之前,std::u64::MAX
等常量不是 u64
类型的关联常量,而是在名为 u64 的模块中定义的常量
。
这是 Rust 没有关联常量时的遗留问题。
从 Rust 1.43 开始,这些常量被定义为相应类型的关联常量。 当前有 an RFC opened to deprecate the modules .现在他们只是"soft-deprecated"和文档注释:
Constant std::u32::MAX
pub const MAX: u32 = u32::max_value(); // 4_294_967_295u32
The largest value that can be represented by this integer type. Use
u32::MAX
instead.
(重点是我的)
另一种方法是使用关联的 const
方法(例如 u32::max_value
),添加这些方法是因为常量方法在关联常量之前可用。这些也是软弃用的,文档说明:
pub const fn max_value() -> u32
This method is soft-deprecated.
Although using it won’t cause compilation warning, new code should use
u32::MAX
instead.Returns the largest value that can be represented by this integer type.
(重点不是我的)
关联常量也可以像您期望的那样通过类型别名访问:
struct Foo;
impl Foo {
const FOO: u32 = 42;
}
type Bar = Foo;
fn main() {
let this_works = Foo::FOO;
let this_also_work = Bar::FOO;
let this_works_too = u32::MAX; // As of Rust 1.43
println!("The answer: {} and {} or {}", this_works, this_also_work, this_works_too);
}
关于types - 为什么类型别名不能使用 Rust 中原始类型的关联常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56840129/