主题
函数与方法
Rust 使用函数和方法来封装可复用代码,函数在作用域外定义,方法绑定在结构体或枚举等类型上。
函数定义与调用
函数使用 fn
关键字定义,支持参数和返回值:
rust
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let result = add(5, 3);
println!("5 + 3 = {}", result);
}
无返回值的函数
Rust 中返回空元组 ()
表示无返回值:
rust
fn greet(name: &str) {
println!("Hello, {}!", name);
}
方法与关联函数
方法定义在 impl
块中,第一个参数通常是 &self
,表示调用该方法的实例:
rust
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn new(width: u32, height: u32) -> Self {
Self { width, height }
}
}
fn main() {
let rect = Rectangle::new(10, 20);
println!("矩形面积: {}", rect.area());
}
函数作为一等公民
Rust 支持将函数作为参数或返回值,也支持闭包:
rust
fn apply<F>(f: F) where F: Fn() {
f();
}
fn main() {
let greeting = || println!("Hello from closure!");
apply(greeting);
}