fn apply_mut<F>(mut f: F)
where
F: FnMut() -> i32,
{
println!("Result: {}", f());
}
fn main() {
let mut x = 1;
let mut closure = || {
x += 1; // 修改外部狀態
x * 2
};
apply_mut(closure); // 使用 closure
}
在這個例子中,閉包 closure 每次被調用都會修改 x 的值,因為它實現了 FnMut trait。
2. 條件結合多個 trait
我們可以結合多個 trait 來限制函數參數的行為。例如:
rust
fn apply_complex<F, G>(f: F, g: G) -> i32
where
F: FnOnce() -> i32,
G: FnMut(i32) -> i32,
{
let value = f(); // 調用 F
g(value) // 調用 G
}
fn main() {
let x = 5;
let double = |num| num * 2; // 函數 g
apply_complex(|| x, double); // 傳入 F 和 G
}
不過,這段程式碼並不會直接輸出結果。在 apply_complex 中調用 g(value) 會計算 double(value),但沒有捕獲並輸出這個結果。如果你希望將結果輸出到控制台,可以稍微修改一下 main 函數,並將 apply_complex 的返回值存儲並打印出來:
rust
fn main() {
let x = 5;
let double = |num| num * 2; // 函數 g
let result = apply_complex(|| x, double); // 傳入 F 和 G
println!("Result: {}", result); // 輸出結果
}
warning: fields buffer and indices are never read
--> src\graphics\internal_canvas.rs:689:9
|
688 | pub struct InstanceArrayView {
| ----------------- fields in this struct
689 | pub buffer: ArcBuffer,
| ^^^^^^
690 | pub indices: ArcBuffer,
| ^^^^^^^
|
= note: InstanceArrayView has a derived impl for the trait Debug, but this is intentionally ignored during dead code analysis
= note: #[warn(dead_code)] on by default
warning: method append is never used
--> src\vfs.rs:112:8
|
97 | pub trait VFS: Debug {
| --- method in this trait
...
112 | fn append(&self, path: &Path) -> GameResult<Box> {
| ^^^^^^
warning: method len is never used
--> src\vfs.rs:149:8
|
140 | pub trait VMetadata {
| --------- method in this trait
...
149 | fn len(&self) -> u64;
| ^^^
warning: ggez (lib) generated 3 warnings
Compiling ggez v0.9.3 (C:\Users\fer52\ggez-master)
error[E0596]: cannot borrow g as mutable, as it is not declared as mutable
--> examples\01_super_simple_1.rs:7:5
|
7 | g(value) // 調用 G
| ^ cannot borrow as mutable
|
help: consider changing this to be mutable
|
1 | fn apply_complex<F, G>(f: F, mut g: G) -> i32
| +++
For more information about this error, try rustc --explain E0596.