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

标签 types rust alias associated-const

编者注:从 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);
}

(Permalink to the playground)

我期望 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);
}

(Permalink to the playground)

关于types - 为什么类型别名不能使用 Rust 中原始类型的关联常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56840129/

相关文章:

python - 在 python 中,是否有某种映射来返回类型的 "False value"?

functional-programming - 在 map 内部使用 if 时如何处理 "if may be missing an else clause"?

ruby - 如何在 Ruby 扩展别名中发出 YAML

memory-management - 什么是Dyon的内存模型?

rust - 匹配一只 ARM 中的两个枚举变体,使用 Option? 绑定(bind)一个变体的字段?

C#:如何为类创建 "aliases"

c# - 在 C# 中使用继承而不是名称别名是否正确?

c# - 已接受的用于处理 Excel 数据的集合

hash - 是否可以为整个整数范围实现通用哈希?

C++ long long 操作