Book Image

Hands-On Functional Programming in Rust

By : Andrew Johnson
Book Image

Hands-On Functional Programming in Rust

By: Andrew Johnson

Overview of this book

Functional programming allows developers to divide programs into smaller, reusable components that ease the creation, testing, and maintenance of software as a whole. Combined with the power of Rust, you can develop robust and scalable applications that fulfill modern day software requirements. This book will help you discover all the Rust features that can be used to build software in a functional way. We begin with a brief comparison of the functional and object-oriented approach to different problems and patterns. We then quickly look at the patterns of control flow, data the abstractions of these unique to functional programming. The next part covers how to create functional apps in Rust; mutability and ownership, which are exclusive to Rust, are also discussed. Pure functions are examined next and you'll master closures, their various types, and currying. We also look at implementing concurrency through functional design principles and metaprogramming using macros. Finally, we look at best practices for debugging and optimization. By the end of the book, you will be familiar with the functional approach of programming and will be able to use these techniques on a daily basis.
Table of Contents (12 chapters)

Understanding Send and Sync traits

In the previous neural network example, we used a static data structure that was shared between threads without being wrapped in a counter or lock. It contained locks, but why was the outer data structure permitted to be shared?

To answer this question, let's first review the rules of ownership:

  • Each value in Rust has a variable that's called its owner
  • There can only be one owner at a time
  • When the owner goes out of scope, the value will be dropped

With these rules in mind, let's try to share a variable across threads, as follows:

use std::thread;

fn main() {
let a = vec![1, 2, 3];

thread::spawn(|| {
println!("a = {:?}", a);
});
}

If we try to compile this, then we will get an error complaining of the following:

closure may outlive the current function, but it borrows `a`, which is owned by the current function...