Book Image

Mastering Rust

By : Vesa Kaihlavirta
Book Image

Mastering Rust

By: Vesa Kaihlavirta

Overview of this book

<p>If concurrent programs are giving you sleepless nights, Rust is your go-to language. Being one of the first ever comprehensive books on Rust, it is filled with real-world examples and explanations, showing you how you can build scalable and reliable programs for your organization.</p> <p>We’ll teach you intermediate to advanced level concepts that make Rust a great language. Improving performance, using generics, building macros, and working with threads are just some of the topics we’ll cover. We’ll talk about the official toolsets and ways to discover more. The book contains a mix of theory interspersed with hands-on tasks, so you acquire the skills as well as the knowledge. Since programming cannot be learned by just reading, we provide exercises (and solutions) to hammer the concepts in.</p> <p>After reading this book, you will be able to implement Rust for your enterprise project, deploy the software, and will know the best practices of coding in Rust.</p>
Table of Contents (22 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

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 = |x: u32| { x*x };
 let square_c3 = |x: u32| -> u32 { x*x };

 let closure_without_vars = || println!("Entered closure without variables");

 println!("square of 4 = {}", square(4));
 println!("square of 4 = {}", square_c1(4));
 println...