rust学习-rust中的保留字

发布于:2025-02-10 ⋅ 阅读:(107) ⋅ 点赞:(0)

rust学习-rust中的保留字

保留字是语言中预定义的标识符,不能用作变量名、函数名或其他自定义标识符,Rust的保留字大致可以分为两类:已使用的保留字和未来可能使用的保留字

已使用的保留字

  1. as:用于类型转换
let num: i32 = 5;
let float_num = num as f64;
  1. break:用于终止循环
loop {
    println!("再次循环");
    break;
}
  1. const:用于定义常量
const MAX_POINTS: u32 = 100_000;
  1. continue:用于跳过当前循环的剩余部分并开始下一次迭代
for i in 0..10 {
    if i % 2 == 0 {
        continue;
    }
    println!("奇数: {}", i);
}
  1. crate:用于指定 crate 根模块
// 在 Cargo.toml 中定义 crate
// Cargo.toml
[package]
name = "my_crate"
version = "0.1.0"
  1. dyn:用于动态分发的 trait 对象
trait Draw {
    fn draw(&self);
}

struct Rectangle;

impl Draw for Rectangle {
    fn draw(&self) {
        println!("绘制矩形");
    }
}

fn draw_item(item: &dyn Draw) {
    item.draw();
}

let rectangle = Rectangle;
draw_item(&rectangle);
  1. else:用于条件语句中的 if 之后的分支
let x = 5;
if x == 5 {
    println!("x 是 5");
} else {
    println!("x 不是 5");
}
  1. enum:用于定义枚举类型
enum Color {
    Red,
    Green,
    Blue,
}

let color = Color::Red;
  1. extern:用于定义外部函数或链接外部库
extern "C" {
    fn printf(format: *const u8, ...) -> i32;
}

fn main() {
    unsafe {
        printf(b"Hello, World!\0".as_ptr());
    }
}
  1. false:布尔常量,表示假
let is_false = false;
  1. fn:用于定义函数
fn add(a: i32, b: i32) -> i32 {
    a + b
}

let sum = add(5, 3);
  1. for:用于循环
for i in 0..3 {
    println!("i: {}", i);
}
  1. if:用于条件语句
let x = 5;
if x > 0 {
    println!("x 是正数");
}
  1. impl:用于实现方法或 trait
struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Point {
        Point { x, y }
    }

    fn distance(&self, other: &Point) -> f64 {
        (((self.x - other.x).pow(2) + (self.y - other.y).pow(2)) as f64).sqrt()
    }
}

let p1 = Point::new(0, 0);
let p2 = Point::new(3, 4);
println!("距离: {}", p1.distance(&p2));
  1. in:用于 for 循环或 match 语句
for i in 0..3 {
    println!("i: {}", i);
}

match 2 {
    1 => println!("一是 1"),
    2 => println!("二是 2"),
    _ => println!("其他"),
}
  1. let:用于声明变量
let x = 5;
let y: i32 = 10;
  1. loop:用于无限循环
loop {
    println!("再次循环");
    break;
}
  1. match:用于模式匹配
let x = 2;
match x {
    1 => println!("一是 1"),
    2 => println!("二是 2"),
    _ => println!("其他"),
}
  1. mod:用于定义模块
mod my_module {
    pub fn say_hello() {
        println!("Hello from my_module!");
    }
}

fn main() {
    my_module::say_hello();
}
  1. move:用于闭包捕获环境
let x = 5;
let y = 10;

let closure = move || {
    println!("x: {}, y: {}", x, y);
};

closure();
  1. mut:用于声明可变变量
let mut x = 5;
x = 10;
  1. pub:用于声明公共项
pub fn public_function() {
    println!("这是公共函数");
}

mod my_mod {
    pub fn public_function() {
        println!("这是 my_mod 中的公共函数");
    }
}
  1. ref:用于在模式匹配中获取引用
let x = 5;
let ref_x = &x;

match ref_x {
    ref r => println!("r 是引用: {:?}", r),
}
  1. return:用于从函数返回值
fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

let sum = add(5, 3);
  1. self:用于表示当前实例
struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Self {
        Point { x, y }
    }

    fn distance_from_origin(&self) -> f64 {
        (self.x.pow(2) + self.y.pow(2)) as f64
    }
}

let p = Point::new(3, 4);
println!("距离原点: {}", p.distance_from_origin());
  1. Self:用于表示当前类型的自身
struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}

let p = Point::new(3, 4);
  1. static:用于定义静态变量
static X: i32 = 5;

fn main() {
    println!("X: {}", X);
}
  1. struct:用于定义结构体
struct Point {
    x: i32,
    y: i32,
}

let p = Point { x: 3, y: 4 };
  1. super:用于访问父模块
mod outer {
    pub fn outer_fn() {
        println!("outer_fn");
    }

    mod inner {
        pub fn inner_fn() {
            super::outer_fn();
            println!("inner_fn");
        }
    }
}

fn main() {
    outer::inner::inner_fn();
}
  1. trait:用于定义 trait

trait(特性)是一种定义共享行为的方式,它类似于其他编程语言中的接口(interface),但更加灵活和强大,trait可定义一组方法签名,这些方法可以在不同的类型中实现,通过这种方式,Rust能够实现多态性,并确保类型安全

trait Draw {
    fn draw(&self);
}

struct Rectangle;

impl Draw for Rectangle {
    fn draw(&self) {
        println!("绘制矩形");
    }
}

fn draw_item(item: &impl Draw) {
    item.draw();
}

let rectangle = Rectangle;
draw_item(&rectangle);
  1. true:布尔常量,表示真
let is_true = true;
  1. type:用于定义类型别名
type Kilometers = i32;

let distance: Kilometers = 5;
  1. unsafe:用于编写不安全的代码
unsafe fn dangerous() {
    println!("这是不安全的代码");
}

fn main() {
    unsafe {
        dangerous();
    }
}
  1. use:用于引入模块
mod my_mod {
    pub fn say_hello() {
        println!("Hello from my_mod!");
    }
}

use my_mod::say_hello;

fn main() {
    say_hello();
}
  1. where:用于指定 trait 约束
fn some_func<T: std::fmt::Display>(t: T) where T: std::fmt::Debug {
    println!("t: {:?}", t);
}

fn main() {
    some_func(5);
}

未来可能使用的保留字

  1. abstract
  2. become
  3. box
  4. do
  5. final
  6. macro
  7. override
  8. priv
  9. typeof
  10. unsized
  11. virtual
  12. yield

这些保留字目前在 Rust 中没有具体的用途,但它们被预留以备将来扩展语言时使用


网站公告

今日签到

点亮在社区的每一天
去签到