O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Closures

Closures give us a way to quickly define small, anonymous functions, which optionally grab some of the variables defined in the outer scope. That's where the name comes from: the variables from the outer scope are "closed over".

Threads are often launched via closures due to their terser syntax and features. The syntax should be familiar to any Ruby programmers, but there are a few Rusty additions.

In a simple form, closures are semantically identical to functions. Here are four similar functions or closures that take and return a value, and two that take no parameters:

fn square(x: u32) -> u32 { x * x}fn function_without_vars() { println!("Entered function without variables");}fn main() { let square_c1 = |x: u32| x*x; let square_c2 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required