为什么类型别名不能使用Rust中原始类型的关联常量?

Fir*_*ife 3 alias types rust associated-const

我有一个类型别名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);
}
Run Code Online (Sandbox Code Playgroud)

(永久链接到操场)

我期望MAX常量也可以从类型别名访问。当我将类型更改为u32时,这将对我有帮助,这将导致代码有两点需要修改,而不仅仅是类型别名的位置。为什么要做出这个决定,而我是否错过了可能使之成为可能的事情?

mca*_*ton 8

诸如std::u64::MAXu64类的常数不是与之相关联的类型常数,而是在称为的模块中定义的常数u64

这是Rust没有关联常量时的遗留问题。当前有一个RFC弃用

实现此目的的“新”方法是使用关联的const方法,这些方法可通过类型别名访问:

use std::u64;

type CardId = u64;

fn main() {
    let this_works = u64::max_value();
    let this_also_work = CardId::max_value();

    println!(
        "Max amount in integer: {} and {}",
        this_works, this_also_work
    );
}
Run Code Online (Sandbox Code Playgroud)

(永久链接到操场)

您也可以通过类型别名访问关联的常量:

struct Foo;

impl Foo {
    const FOO: u32 = 42;
}

type Bar = Foo;

fn main() {
    let this_works = Foo::FOO;
    let this_also_work = Bar::FOO;

    println!("The answer: {} and {}", this_works, this_also_work);
}
Run Code Online (Sandbox Code Playgroud)

(永久链接到操场)


hel*_*low 6

这是因为std::u64::MAX是模块常量,而不是类型常量。

max_value如果要与类型别名一起使用,可以使用:

use std::u64;

type CardId = u64;

fn main() {
    let this_works = u64::max_value();
    let this_does_work_as_well = CardId::max_value();

    println!("Max amount in integer: {} and {}", this_works, this_does_work_as_well);
}
Run Code Online (Sandbox Code Playgroud)