在Rust中,函数传播状态可以通过使用返回值、引用参数和全局变量来实现。
fn divide(x: i32, y: i32) -> Result<i32, String> {
if y == 0 {
return Err(String::from("Cannot divide by zero"));
}
Ok(x / y)
}
fn main() {
let result = divide(10, 2);
match result {
Ok(value) => println!("Result: {}", value),
Err(error) => println!("Error: {}", error),
}
}
fn increment(x: &mut i32) {
*x += 1;
}
fn main() {
let mut value = 10;
increment(&mut value);
println!("Value: {}", value);
}
use lazy_static::lazy_static;
use std::sync::Mutex;
lazy_static! {
static ref STATE: Mutex<i32> = Mutex::new(0);
}
fn increment() {
let mut state = STATE.lock().unwrap();
*state += 1;
}
fn main() {
increment();
let state = STATE.lock().unwrap();
println!("State: {}", *state);
}
以上是三种常见的在Rust中传播状态的方法。具体使用哪种方法取决于具体的场景和需求。
领取专属 10元无门槛券
手把手带您无忧上云