当前位置: 首页 > news >正文

Rust 语法基础教程

Rust 语法基础教程

Rust 是一门系统编程语言,以内存安全、零成本抽象和并发安全著称。本文将介绍 Rust 的基础语法。

1. 变量与可变性

不可变变量

let x = 5;
// x = 6; // 错误:不能修改不可变变量

可变变量

let mut y = 5;
y = 6; // 正确:可以修改可变变量

常量

const MAX_POINTS: u32 = 100_000;

变量遮蔽 (Shadowing)

let x = 5;
let x = x + 1; // 遮蔽前一个 x
let x = x * 2; // 再次遮蔽

2. 数据类型

标量类型

// 整数类型
let a: i32 = 42;
let b: u64 = 100;// 浮点类型
let c: f64 = 3.14;
let d = 2.0; // f64 默认类型// 布尔类型
let e: bool = true;
let f = false;// 字符类型
let g: char = 'z';
let h = '😻';

复合类型

// 元组
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup; // 解构
let first = tup.0; // 索引访问// 数组
let arr: [i32; 5] = [1, 2, 3, 4, 5];
let same_value = [3; 5]; // [3, 3, 3, 3, 3]
let first_element = arr[0];

3. 函数

// 基本函数
fn greet(name: &str) {println!("Hello, {}!", name);
}// 带返回值的函数
fn add(a: i32, b: i32) -> i32 {a + b // 表达式,无分号
}// 多返回值
fn calculate(x: i32, y: i32) -> (i32, i32) {(x + y, x - y)
}

4. 控制流

if 表达式

let number = 6;if number % 4 == 0 {println!("number is divisible by 4");
} else if number % 3 == 0 {println!("number is divisible by 3");
} else {println!("number is not divisible by 4 or 3");
}// if 作为表达式
let condition = true;
let number = if condition { 5 } else { 6 };

循环

// loop 循环
let mut counter = 0;
let result = loop {counter += 1;if counter == 10 {break counter * 2;}
};// while 循环
let mut number = 3;
while number != 0 {println!("{}!", number);number -= 1;
}// for 循环
let a = [10, 20, 30, 40, 50];
for element in a.iter() {println!("the value is: {}", element);
}// 范围循环
for number in 1..4 {println!("{}!", number);
}

5. 所有权 (Ownership)

基本规则

  1. Rust 中的每一个值都有一个被称为其所有者的变量
  2. 值在任一时刻有且只有一个所有者
  3. 当所有者离开作用域,这个值将被丢弃
// 移动 (Move)
let s1 = String::from("hello");
let s2 = s1; // s1 被移动到 s2,s1 不再有效// 克隆 (Clone)
let s1 = String::from("hello");
let s2 = s1.clone(); // 深拷贝// 引用 (References)
let s1 = String::from("hello");
let len = calculate_length(&s1); // 借用fn calculate_length(s: &String) -> usize {s.len()
}

6. 结构体 (Struct)

// 定义结构体
struct User {username: String,email: String,sign_in_count: u64,active: bool,
}// 创建实例
let user1 = User {email: String::from("someone@example.com"),username: String::from("someusername123"),active: true,sign_in_count: 1,
};// 元组结构体
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);// 方法
impl User {fn new(email: String, username: String) -> User {User {email,username,active: true,sign_in_count: 1,}}fn is_active(&self) -> bool {self.active}
}

7. 枚举 (Enum)

// 基本枚举
enum IpAddrKind {V4,V6,
}// 带数据的枚举
enum IpAddr {V4(u8, u8, u8, u8),V6(String),
}// Option 枚举
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;// match 表达式
fn value_in_cents(coin: Coin) -> u8 {match coin {Coin::Penny => 1,Coin::Nickel => 5,Coin::Dime => 10,Coin::Quarter => 25,}
}

8. 错误处理

// Result 类型
use std::fs::File;
use std::io::ErrorKind;let f = File::open("hello.txt");
let f = match f {Ok(file) => file,Err(error) => match error.kind() {ErrorKind::NotFound => match File::create("hello.txt") {Ok(fc) => fc,Err(e) => panic!("Problem creating the file: {:?}", e),},other_error => panic!("Problem opening the file: {:?}", other_error),},
};// unwrap 和 expect
let f = File::open("hello.txt").unwrap();
let f = File::open("hello.txt").expect("Failed to open hello.txt");

9. 泛型、Trait 和生命周期

// 泛型函数
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {let mut largest = list[0];for &item in list {if item > largest {largest = item;}}largest
}// Trait 定义
trait Summary {fn summarize(&self) -> String;
}// Trait 实现
struct NewsArticle {headline: String,content: String,
}impl Summary for NewsArticle {fn summarize(&self) -> String {format!("{}: {}", self.headline, self.content)}
}

总结

Rust 的语法设计注重安全性和性能,通过所有权系统、类型系统和借用检查器确保内存安全。掌握这些基础语法是学习 Rust 的重要第一步。关于泛型,trait,所有权,生命周期在后面会详细讲解

http://www.lryc.cn/news/622706.html

相关文章:

  • AI应用安全 - Prompt注入攻击
  • [1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
  • 【LeetCode题解】LeetCode 35. 搜索插入位置
  • Dify实战应用指南(上传需求稿生成测试用例)
  • Jenkins常见问题及解决方法
  • STM32 延时函数详解
  • 343整数拆分
  • 后量子密码算法ML-DSA介绍及开源代码实现
  • 【Qt开发】常用控件(四)
  • 算法提升之树上问题-(tarjan求LCA)
  • 基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
  • MySQL 配置性能优化赛技术文章
  • Win10、Win11电脑之间无法Ping通解决办法
  • 设计模式之【快速通道模式】,享受VIP的待遇
  • Python - 100天从新手到大师:第十一天常用数据结构之字符串
  • OpenCV Python——图像拼接(一)(图像拼接原理、基础知识、单应性矩阵 + 图像变换 + 拼接)
  • redis基本类型之哈希
  • 爬机 验证服务器是否拒绝请求
  • 衡石使用指南嵌入式场景实践之仪表盘嵌入
  • 【Docker项目实战】使用Docker部署Notepad轻量级记事本
  • 《吃透 C++ 类和对象(中):const 成员函数与取地址运算符重载解析》
  • js原生实现手写签名与使用signature_pad库实现手写签名
  • 【Java Web 快速入门】十一、Spring Boot 原理
  • Flutter开发 网络请求
  • Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
  • Flutter Provider 模式实现:基于 InheritedWidget 的状态管理实现
  • SQL183 近三个月未完成试卷数为0的用户完成情况
  • 力扣(LeetCode) ——142. 环形链表 II(C语言)
  • JavaWeb 30 天入门:第十一天 ——Java 反射机制详解
  • 【环境变量与程序地址空间详解】