9951 explained code solutions for 126 technologies


rustHow to define closure return type in RUst


In Rust, closure return types can be defined by using the -> operator followed by the return type. For example, the following closure returns a String:

let closure = |x| -> String { format!("The value of x is {}", x) };

The return type of the closure can also be inferred by the compiler, so the above example can be written as:

let closure = |x| { format!("The value of x is {}", x) };

The return type of the closure can also be explicitly set to () if the closure does not return a value. For example:

let closure = |x| -> () { println!("The value of x is {}", x) };

Helpful links

Edit this code on GitHub