Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Hands-On Functional Programming in Rust

You're reading from   Hands-On Functional Programming in Rust Build modular and reactive applications with functional programming techniques in Rust 2018

Arrow left icon
Product type Paperback
Published in May 2018
Publisher Packt
ISBN-13 9781788839358
Length 249 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Andrew Johnson Andrew Johnson
Author Profile Icon Andrew Johnson
Andrew Johnson
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Functional Programming – a Comparison 2. Functional Control Flow FREE CHAPTER 3. Functional Data Structures 4. Generics and Polymorphism 5. Code Organization and Application Architecture 6. Mutability, Ownership, and Pure Functions 7. Design Patterns 8. Implementing Concurrency 9. Performance, Debugging, and Metaprogramming 10. Assessments 11. Other Books You May Enjoy

Using pure functions

Pure functions are the second technique that we recommend to prevent hard-to-reproduce bugs. Pure functions can be thought of as an extension of the avoid side-effects principle. The definition of a pure function is a function where the following is true:

  • No changes are caused outside of the function (no side-effects)
  • The return value does not depend on anything but the function parameters

Here are some examples of pure functions:

fn p0() {}

fn p1() -> u64 {
444
}

fn p2(x: u64) -> u64 {
x * 444
}

fn p3(x: u64, y: u64) -> u64 {
x * 444 + y
}

fn main()
{
p0();
p1();
p2(3);
p3(3,4);
}

Here are some examples of impure functions:

use std::cell::Cell;

static mut blah: u64 = 3;
fn ip0() {
unsafe {
blah = 444;
}
}

fn ip1(c: &Cell<u64>) {
c.set(333);
}

fn main()
{
ip0();
let r = Cell::new(3);
ip1(&r);
ip1(&r);
}

Rust does...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image