目录认识生命周期返回值与错误处理panic深入剖析可恢复的错误Result包和模块包Crate模块Module使用use及受限可见性注释和文档格式化输出认识生命周期什么是生命周期?定义:生命周期是Rust中用来管理引用的有效范围的概念。作用:确保引
// 定义一个带有生命周期注解的函数
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
多个生命周期注解:当函数或结构体涉及多个引用时,需要明确指定每个引用的生命周期。
// 定义一个带有多个生命周期注解的函数
fn longest_with_an_announcement<'a, 'b>(x: &'a str, y: &'a str, ann: &'b str) -> &'a str {
println!("Announcement! {}", ann);
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let string1 = String::from("hello");
let string2 = String::from("world");
let result = longest_with_an_announcement(string1.as_str(), string2.as_str(), "Drum roll please");
println!("The longest string is {}", result);
}
panic! 宏
fn divide_by_zero() {
panic!("Attempted to divide by zero");
}
fn main() {
divide_by_zero();
}
panic! 的工作机制
fn main() {
let v = vec![1, 2, 3];
// 尝试访问越界的元素
let result = v.get(5).expect("Index out of bounds");
println!("Result: {:?}", result);
}
Result 枚举
Result 的使用
fn divide(a: isize, b: isize) -> Result<isize, &'static str> {
if b == 0 {
Err("Cannot divide by zero")
} else {
Ok(a / b)
}
}
fn main() {
let result = divide(10, 2);
match result {
Ok(value) => println!("Result: {}", value),
Err(e) => println!("Error: {}", e),
}
}
unwrap 和 expect
unwrap
:用于从 Result 中提取值,如果结果是 Err,则触发 panic!。expect
:与 unwrap 类似,但可以提供自定义的错误消息。fn main() {
let result = divide(10, 0);
let value = result.unwrap_or_else(|e| {
println!("Error: {}", e);
0
});
println!("Result: {}", value);
}
map
:用于在 Ok 值上应用函数。and_then
:用于在 Ok 值上应用另一个 Result 函数。fn square(x: isize) -> isize {
x * x
}
fn main() {
let result = divide(10, 2);
let squared_result = result.map(square);
match squared_result {
Ok(value) => println!("Squared result: {}", value),
Err(e) => println!("Error: {}", e),
}
}
fn divide(a: isize, b: isize) -> Result<isize, &'static str> {
if b == 0 {
Err("Cannot divide by zero")
} else {
Ok(a / b)
}
}
fn calculate(a: isize, b: isize) -> Result<isize, &'static str> {
let result = divide(a, b)?;
Ok(result * 2)
}
fn main() {
match calculate(10, 2) {
Ok(value) => println!("Result: {}", value),
Err(e) => println!("Error: {}", e),
}
}
什么是包(Crate)
Cargo.toml
文件和一个入口文件(如 src/main.rs
或 src/lib.rs
)。创建一个简单的 crate
cargo new my_crate --bin
cd my_crate
Cargo.toml 文件
[package]
name = "my_crate"
version = "0.1.0"
authors = ["Your Name <your.email@example.com>"]
edition = "2018"
[dependencies]
入口文件
// src/main.rs
fn main() {
println!("Hello, world!");
}
什么是模块(Module)
创建模块
// src/main.rs
mod greeting;
fn main() {
greeting::say_hello();
}
// src/greeting.rs
pub fn say_hello() {
println!("Hello, world!");
}
模块路径
mod
关键字定义模块时,可以使用相对路径。crate
根目录开始的路径。// src/main.rs
mod greeting;
fn main() {
greeting::say_hello();
}
// src/greeting.rs
pub fn say_hello() {
println!("Hello, world!");
}
引入模块
// src/main.rs
mod greeting;
use greeting::say_hello;
fn main() {
say_hello();
}
// src/greeting.rs
pub fn say_hello() {
println!("Hello, world!");
}
别名
// src/main.rs
mod greeting;
use greeting::say_hello as greet;
fn main() {
greet();
}
// src/greeting.rs
pub fn say_hello() {
println!("Hello, world!");
}
可见性修饰符
// src/main.rs
mod greeting;
use greeting::say_hello;
fn main() {
say_hello();
}
// src/greeting.rs
pub fn say_hello() {
println!("Hello, world!");
}
可见性层次
// src/main.rs
mod greeting;
use greeting::say_hello;
fn main() {
say_hello();
}
// src/greeting.rs
pub mod greeting {
pub fn say_hello() {
println!("Hello, world!");
}
}
///
或 /*!
开头的注释。// src/main.rs
mod greeting;
use greeting::say_hello;
fn main() {
say_hello();
}
// src/greeting.rs
/// Prints a greeting message.
pub fn say_hello() {
println!("Hello, world!");
}
cargo doc
:可以生成文档。cargo doc --open
格式化字符串:使用 format!
宏生成格式化的字符串。
fn main() {
let name = "Alice";
let age = 30;
let message = format!("Hello, my name is {} and I am {} years old.", name, age);
println!("{}", message);
}
writeln!
宏输出格式化的字符串。fn main() {
let name = "Alice";
let age = 30;
writeln!(std::io::stdout(), "Hello, my name is {} and I am {} years old.", name, age).unwrap();
}
printf!
宏输出格式化的字符串。fn main() {
let name = "Alice";
let age = 30;
printf!("Hello, my name is %s and I am %d years old.\n", name, age);
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!