Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading