Rust 原始标识符介绍

RustRustBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习Rust中的原始标识符,它允许我们在通常不允许使用关键字作为标识符的情况下使用关键字,例如变量名或函数名,特别是当旧版本的Rust与新关键字冲突时。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,并通过 rustc main.rs &&./main 进行编译和运行。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/ErrorHandlingandDebuggingGroup(["Error Handling and Debugging"]) rust(("Rust")) -.-> rust/ProjectManagementandOrganizationGroup(["Project Management and Organization"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/ErrorHandlingandDebuggingGroup -.-> rust/error_propagation("Error Propagation") rust/ProjectManagementandOrganizationGroup -.-> rust/cargo_crates("Cargo and Crates") subgraph Lab Skills rust/function_syntax -.-> lab-99288{{"Rust 原始标识符介绍"}} rust/expressions_statements -.-> lab-99288{{"Rust 原始标识符介绍"}} rust/method_syntax -.-> lab-99288{{"Rust 原始标识符介绍"}} rust/error_propagation -.-> lab-99288{{"Rust 原始标识符介绍"}} rust/cargo_crates -.-> lab-99288{{"Rust 原始标识符介绍"}} end

原始标识符

和许多编程语言一样,Rust 也有 “关键字” 的概念。这些标识符对语言来说有特定含义,所以你不能在变量名、函数名等地方使用它们。原始标识符允许你在通常不允许使用关键字的地方使用关键字。当 Rust 引入新关键字,而使用旧版本 Rust 的库中有一个变量或函数与新版本中引入的关键字同名时,这一点特别有用。

例如,考虑一个用 2015 版 Rust 编译的名为 foo 的包,它导出了一个名为 try 的函数。这个关键字在 2018 版中被用于一个新特性,所以如果没有原始标识符,我们就无法给这个函数命名。

extern crate foo;

fn main() {
    foo::try();
}

你会得到如下错误:

error: expected identifier, found keyword `try`
 --> src/main.rs:4:4
  |
4 | foo::try();
  |      ^^^ expected identifier, found keyword

你可以使用原始标识符来这样写:

extern crate foo;

fn main() {
    foo::r#try();
}

总结

恭喜你!你已完成 “原始标识符” 实验。你可以在 LabEx 中练习更多实验来提升你的技能。