rust - 除了新关键字之外,原始标识符的用例有哪些?

标签 rust rust-2018

与 Rust 2018 一样,我们现在有 raw identifiers :

This feature is useful for a few reasons, but the primary motivation was inter-edition situations. For example, try is not a keyword in the 2015 edition, but is in the 2018 edition. So if you have a library that is written in Rust 2015 and has a try function, to call it in Rust 2018, you'll need to use the raw identifier.

除上述之外,还有其他优势吗?是否有计划使关键字与上下文相关,例如您可以使用 type 作为变量的标识符吗?为什么我应该使用像 r#type 这样的神秘语法而不是 ty 或其他东西?

最佳答案

Why I should use a cryptic syntax like r#type instead of ty or something else?

有时字段名称在 Rust 程序之外使用。例如,当使用 Serde 序列化数据时,字段名称用于输出(例如 JSON)。因此,如果您需要 JSON 输出:

"type": 27,

...那么原始标识符可以帮助您:

#[derive(Serialize)]
struct Foo {
    r#type: u32,
}

另一方面...Serde 已经有办法实现您想要的:the #[serde(rename = "name")] attribute .保留的 Rust 关键字是引入此属性的原因之一。

#[derive(Serialize)]
struct Foo {
    #[serde(rename = "type")]
    ty: u32,
}

同样,Debug 输出也在其输出中使用字段名称。所以如果你想要输出 Foo { type: 27 } ,你可以使用原始标识符:

#[derive(Debug)]
struct Foo {
    r#type: u32,
}

另一方面...如果准确的 Debug 输出对您来说很重要,您可以简单地自己实现它:

impl fmt::Debug for Foo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Foo")
            .field("type", &self.ty)
            .finish()
    }
}

所以在实践中,我不明白为什么有人会为此目的使用原始标识符,因为你必须在任何使用该名称的地方使用奇怪的 r# 语法。以另一种方式解决这个特定问题可能更容易。

因此,据我所知,“使用来自另一个版本的 API”是原始标识符的唯一实际用例。拥有这样的语法“只为案例”是一个不错的选择不过。

关于rust - 除了新关键字之外,原始标识符的用例有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51000263/

相关文章:

rust - 如何定义多层 crate ?

rust - 如何在不丢锁的情况下解锁rwlock

rust - 围绕异步和流的生命

rust - 红 bean 杉应用程序-rustwasm错误未捕获的RangeError : Maximum call stack size exceeded

rust - CSV 和数据流的生命周期不够长

rust - 迭代Rust Vec的首选方法?

rust - 如何在 Rust 2018 中惯用地为箱子起别名?

windows - 检查文件是否是 Windows 上 Rust 2018 中的符号链接(symbolic link)

module - use 关键字中的有效路径根是什么?