Rust 中的关键字及示例

ops/2024/9/23 16:52:26/

1. 常见关键字

  • as: 用于类型转换,例如将一个值从一种类型转换为另一种类型。
rust">let x: i32 = 42;
let y: u8 = x as u8;
  • break: 用于提前退出循环。
rust">for i in 0..10 {if i == 5 {break;}
}
  • const: 定义一个常量,常量的值在编译时就确定,不会在运行时改变。
rust">const MAX_POINTS: u32 = 100_000;
  • continue: 跳过当前循环中的剩余部分,直接进入下一次循环迭代。
rust">for i in 0..10 {if i % 2 == 0 {continue;}println!("{}", i);
}
  • crate: 表示当前包或库的根模块,通常用于定义或引用其他模块。
rust">pub fn my_function() {println!("This is a function in the crate root.");
}
  • else: 与 if 搭配使用,表示条件不满足时执行的代码块。
rust">if x > 5 {println!("Greater than 5");
} else {println!("Not greater than 5");
}
  • enum: 定义一个枚举类型,它可以包含多个不同类型的变体(variants)。
rust">enum Direction {Up,Down,Left,Right,
}
  • extern: 用于外部函数或变量的声明,通常用于与 C 语言的交互。
rust">extern "C" {fn printf(format: *const u8, ...) -> i32;
}
  • false: 布尔值字面值。
rust">let a = false;
  • fn: 定义一个函数。
rust">fn my_function() {println!("Hello, world!");
}
  • for: 用于循环,通常与迭代器结合使用。
rust">for i in 0..5 {println!("{}", i);
}
  • if: 条件语句,根据表达式的真假选择执行的代码块。
rust">if x > 5 {println!("Greater than 5");
}
  • impl: 实现一个 trait 或为一个类型实现方法。
rust">struct MyStruct;impl MyStruct {fn new() -> MyStruct {MyStruct}
}
  • in: for 循环语法。
rust">for i in vec![1,2,3] {println!("{}", i);
}
  • let: 绑定一个值到变量。
rust">let x = 5;
  • loop: 定义一个无限循环,可以用 break 退出循环。
rust">loop {println!("This will print forever!");break; // Exit the loop
}
  • match: 模式匹配,类似于 switch/case 语句。
rust">match x {1 => println!("One"),2 => println!("Two"),_ => println!("Something else"),
}
  • mod: 定义一个模块,模块是代码的组织单位。
rust">mod my_module {pub fn my_function() {println!("Hello from the module!");}
}
  • move: 使闭包获取其捕获项的所有权,而不是借用。
rust">let x = vec![1, 2, 3];
// 使用 move 将 x 的所有权移动到闭包中
let equal_to_x = move |z| z == x;
// 此时 x 已经被移动到闭包中,不能在此处再访问 x
// println!("{:?}", x); // 这行代码会报错
  • mut: 标记一个变量是可变的。
rust">let mut x = 5;
x = 6;
  • pub: 公开一个模块、函数或变量,使其可以从其他模块访问。
rust">pub fn public_function() {println!("This function is public!");
}
  • return: 从函数返回一个值。
rust">fn my_function() -> i32 {return 5;
}
  • Self: 定义或实现 trait 的类型的类型别名。
rust">impl Rectangle {fn new(width: u32, height: u32) -> Self {Self { width, height } // `Self` 指代 `Rectangle`}
}
  • self: 表示方法本身或当前模块。
rust">struct Rectangle {width: u32,height: u32,
}
impl Rectangle {fn area(&self) -> u32 {self.width * self.height // `self` 指代 `Rectangle` 的实例}
}
  • static: 表示全局变量或在整个程序执行期间保持其生命周期。
rust">static HELLO: &str = "Hello, world!";
let s: &'static str = "Hello, world!";
  • struct: 定义一个结构体。
rust">struct MyStruct {field1: i32,field2: f64,
}
  • super: 表示当前模块的父模块。
rust">mod parent {pub struct ParentStruct {pub name: String,}pub fn hello() {println!("Hello from parent module");}pub mod child {pub fn create_parent_struct(name: &str) -> super::ParentStruct {super::ParentStruct { name: name.to_string() } // 访问父模块中的结构体}pub fn hello_from_child() {super::hello(); // 使用 `super` 访问父模块中的 `hello` 函数}}
}fn main() {parent::child::hello_from_child();let parent_struct = parent::child::create_parent_struct("Rust");println!("Created ParentStruct with name: {}", parent_struct.name);
}
  • trait: 定义一组方法的集合,类似于接口。
rust">trait MyTrait {fn do_something(&self);
}
  • true: 布尔值字面值。
rust">let bool = true;
  • use: 导入一个模块、类型或函数到当前作用域。
rust">use std::collections::HashMap;
  • where: 为泛型或类型约束指定条件。
rust">fn my_function<T>(x: T) where T: std::fmt::Display {println!("{}", x);
}
  • while: 定义一个循环,当条件为真时继续执行。
rust">while x < 10 {x += 1;
}

2. 特殊关键字

  • unsafe: 用于声明一个不安全的代码块,允许执行一些通常被禁止的操作,例如解引用裸指针。
rust">let p: *const i32 = &10;
unsafe {println!("p points to: {}", *p);
}
  • async: 用于定义一个异步函数,返回一个 Future
rust">async fn my_async_function() {// asynchronous code
}
  • await: 等待一个异步操作完成。
rust">my_async_function().await;
  • dyn: 用于动态分发,实现类似于面向对象语言中的多态性。
rust">fn my_function(p: &dyn MyTrait) {p.do_something();
}
  • ref: 引用模式匹配中的值。
rust">let tuple = (42, "hello");
let (x, ref y) = tuple;
  • type: 定义一个类型别名。
rust">type Kilometers = i32;
  • union: 定义一个联合体,允许一个数据结构在同一位置存储不同类型的数据。
rust">union MyUnion {i: i32,f: f32,
}

3. 保留但未使用的关键字

这些关键字在当前 Rust 版本中没有使用,但它们可能在将来被采用,因此不能作为标识符使用:

  • abstract
  • become
  • box
  • do
  • final
  • macro
  • override
  • priv
  • try
  • typeof
  • unsized
  • virtual
  • yield

http://www.ppmy.cn/ops/107022.html

相关文章

cmake命令交叉编译opencv

1.安装交叉编译工具gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu。 2.解压opencv库&#xff0c;在目录中新建build 3.进入build目录&#xff0c;打开终端&#xff0c;输入命令&#xff1a; cmake ../ -D CMAKE_C_COMPILER/home/KAS-300/gcc-linaro-7.5.0-2019.12-x8…

【Python知识宝库】迭代器与生成器:高效处理大数据集

&#x1f3ac; 鸽芷咕&#xff1a;个人主页 &#x1f525; 个人专栏: 《C干货基地》《粉丝福利》 ⛺️生活的理想&#xff0c;就是为了理想的生活! 文章目录 前言一、迭代器&#xff1a;逐个访问数据的艺术1. 迭代器的定义2. 自定义迭代器3. 迭代器的优势 二、生成器&#xff…

AFSim仿真系统---向导参考指南 (1)

向导参考指南 向导参考指南列出了包含在向导中的功能&#xff0c;并按各种类别进行了组织。 启动 命令行选项 1 命令行参数 - 向导 用法&#xff1a; wizard.exe [ <file_name.txt> ][ <project_file.afproj> ]{ -console } <file_name1.txt> <file_n…

SpringMVC基于注解使用

01-拦截器介绍 首先在pom.xml里面加入springmvc的依赖 创建拦截类 在spring-mvc.xml配置拦截器配置 创建控制类测试 拦截器中处理方法之前的方法介绍 拦截器中处理方法之后&#xff0c;渲染之前的方法介绍 拦截器中处理方法之后&#xff0c;渲染之后的方法介绍 判断拦截器和过…

redis缓存预热、缓存穿透的详细教程

前言 作此篇主要在于关于redis的缓存预热、缓存雪崩、缓存击穿和缓存穿透在面试中经常遇到&#xff0c;工作中也是经常遇到。中级程序员基本上不可避免要克服的几个问题&#xff0c;希望一次性解释清楚 缓存预热 MySQL加入新增100条记录&#xff0c;一般默认以MySQL为准为底单…

如何在Excel中创建一个VBA宏,并设置一个按钮来执行这个宏

下面是一个详细的步骤指南 步骤1&#xff1a;创建VBA宏 1. 打开Excel并按 Alt F11 打开VBA编辑器。 2. 在VBA编辑器中&#xff0c;选择 Insert > Module 来插入一个新的模块。 3. 将以下代码粘贴到模块中&#xff1a; vba Sub CreateNewSheet() 声明一个工作表对象Dim …

SAP ABAP 程序迁移工具 SAPLINK ABAP GIT

SAP ABAP 程序迁移工具 SAPLINK ABAP GIT 1. saplink 这个工具功能挺强大的. 但是使用起来有点麻烦, 需要针对不同的开发对象导入不同的插件.才能处理特定的对象. 而且版本还在不断变化. saplink 项目地址&#xff1a;https://github.com/sapmentors/SAPlink saplink plugin…

【深度学习 CV方向】图像算法工程师 职业发展路线,以及学习路线

图像算法工程师的职业发展路线通常可以分为以下几个阶段&#xff1a; 初级图像算法工程师&#xff1a; 技能要求&#xff1a;掌握基本的图像处理算法和编程能力&#xff0c;能够在指导下完成简单的图像算法项目。对于常见的图像算法&#xff0c;如滤波、边缘检测、图像分割等有…