It looks like you're asking about Box<dyn fn> in Rust, but the notation Box<dyn fn> isn't quite valid as-is. I'll clarify what you might be trying to do and explain how to work with function pointers, trait objects, and Box in Rust.
let x = 10;
let add_x = |y| y + x; // 捕捉外部變數 x
println!("{}", add_x(5)); // 輸出 15
What does Box<dyn fn> mean?
fn is the type of a function pointer in Rust. For example, fn(i32) -> i32 is a function pointer type that points to a function taking an i32 and returning an i32.
The dyn keyword is used to create trait objects, like Box<dyn Trait>, where Trait is a trait.
However, fn by itself is not a trait but a function pointer type, so dyn fn is not valid syntax.
Possible intentions
1. You want a boxed function pointer (boxed fn type)
If you want to box a function pointer, you just do:
rust
let f: Box<fn(i32) -> i32> = Box::new(|x| x + 1);
Here, you have a boxed function pointer. You can call it like so:
rust
let result = f(2); // result is 3
Note: function pointers implement the Copy trait, so boxing them is often unnecessary unless you want to own them on the heap for some reason.
2. You want a boxed trait object for a function-like trait (e.g. Fn)
If you want to store any callable closure or function dynamically, you typically use:
rust
let f: Box<dyn Fn(i32) -> i32> = Box::new(|x| x + 1);
Then you can call it as:
rust
let result = f(2);
Here, dyn Fn(i32) -> i32 is a trait object representing any callable with signature Fn(i32) -> i32.
Summary
What you want
How to write it
Explanation
Box a function pointer
Box<fn(i32) -> i32>
Boxes a function pointer (fixed function)
Box any callable (function/closure)
Box<dyn Fn(i32) -> i32>
Boxes a trait object for callable trait
Box<dyn fn>
invalid syntax
fn is not a trait, so you can't use dyn with it
If you need an example snippet or have a specific case in mind, feel free to share more details!
let f: Box<dyn Fn(i32) -> i32> = Box::new(|x| x + 1);
let result = f(5); // 呼叫 closure,結果是 6
fn main() {
let mut closures: Vec<Box<dyn Fn(i32) -> i32>> = Vec::new();
closures.push(Box::new(|x| x + 1));
closures.push(Box::new(|x| x * 2));
closures.push(Box::new(|x| x * x));
for c in closures.iter() {
println!("{}", c(3));
}
}