KenSmooth
KenSmooth

Reputation: 285

Closure with Box<T> arguments in Rust

I want to know how to code Closure(function) with Box argument in Rust.

For just , it's simple.

fn main() {
    let a = 5;
    let double = |x| 2 * x;
    let b = double(a); //10
}

now, for Box

fn main() {
    let a = Box::new(5);
    let double = |x| 2 * x; //how to write?
    let b = double(a);
}

I don't know what is the adequate or smart way to code, and for unknown reason, the official document or Google did not help.

Please advise.

Upvotes: 1

Views: 85

Answers (1)

at54321
at54321

Reputation: 11756

Here is an example how you can do that:

fn main() {
    let a = Box::new(5);
    let double = |x: Box<i32>| 2 * *x;
    let b = double(a);
    print!("{b}")
}

First, you need to specify the closure parameter type in this case. Instead of Box<i32>, you can also write Box<_>.

Next, you need to get the value owned by the Box via *x.

Upvotes: 1

Related Questions