Skip to Content
Rust Programming By Example
book

Rust Programming By Example

by Guillaume Gomez, Antoni Boucher
January 2018
Beginner to intermediate
454 pages
10h 8m
English
Packt Publishing
Content preview from Rust Programming By Example

Playing with mutable borrows

The first one works just like OpenOptions:

struct Number(u32);

impl Number {
    fn new(nb: u32) -> Number {
        Number(nb)
    }

    fn add(&mut self, other: u32) -> &mut Number {
        self.0 += other;
        self
    }

    fn sub(&mut self, other: u32) -> &mut Number {
        self.0 -= other;
        self
    }

    fn compute(&self) -> u32 {
        self.0
    }
}

If you wonder about self.0, just remember that it's how you access a tuple field.

And then you can call it as follow:

let nb = Number::new(0).add(10).sub(5).add(12).compute();
assert_eq!(nb, 17);

This is the first way to do it.

You'll note that you need to add an ending method so that you can transform your mutable borrow into an object (otherwise, you'll have a borrow issue).

Let's now take a look at the second way to ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Rust Programming Cookbook

Rust Programming Cookbook

Claus Matzinger
Rust Web Programming

Rust Web Programming

Maxwell Flitton

Publisher Resources

ISBN: 9781788390637Supplemental Content