Learning Rust

Book description

Start building fast and robust applications with the power of Rust by your side

About This Book

  • Get started with the language to build scalable and high performance applications
  • This book will help C#/C++ developers gain better performance and memory management
  • Discover the power of Rust when developing concurrent applications for large and scalable software

Who This Book Is For

The book is for absolute beginners to Rust, who want to build high performance, concurrent applications for their projects. It is suitable for developers who have a basic knowledge of programming and developers who are using the C#/C++ language to write their applications. No knowledge of Rust is expected.

What You Will Learn

  • Set up Rust for Windows, Linux, and OS X
  • Write effective code using Rust
  • Expand your Rust applications using libraries
  • Interface existing non-Rust libraries with your Rust applications
  • Use the standard library within your applications
  • Understand memory management within Rust and speed efficiency when passing variables
  • Create more complex data types
  • Study concurrency in Rust with multi-threaded applications and sync threading techniques to improve the performance of an application problem

In Detail

Rust is a highly concurrent and high performance language that focuses on safety and speed, memory management, and writing clean code. It also guarantees thread safety, and its aim is to improve the performance of existing applications. Its potential is shown by the fact that it has been backed by Mozilla to solve the critical problem of concurrency.

Learning Rust will teach you to build concurrent, fast, and robust applications. From learning the basic syntax to writing complex functions, this book will is your one stop guide to get up to speed with the fundamentals of Rust programming. We will cover the essentials of the language, including variables, procedures, output, compiling, installing, and memory handling.

You will learn how to write object-oriented code, work with generics, conduct pattern matching, and build macros. You will get to know how to communicate with users and other services, as well as getting to grips with generics, scoping, and more advanced conditions. You will also discover how to extend the compilation unit in Rust.

By the end of this book, you will be able to create a complex application in Rust to move forward with.

Style and approach

This comprehensive book will focus on the Rust syntax, functions, data types, and conducting pattern matching for programmers. It is divided into three parts and each part of the book has an objective to enable the readers to create their own applications at an appropriate level, ultimately towards creating complex applications.

Table of contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the example code
      2. Errata
      3. Piracy
      4. Questions
  2. Introducing and Installing Rust
    1. Installing Rust
      1. Installing rustup on Linux
      2. gcc prerequisites
        1. Testing your installation
      3. Integrated Development Environment
    2. Your first Rust project
      1. Structure of a Rust project
      2. Automating things
        1. Creating a binary package using Cargo
      3. Using Cargo to build and run an application
        1. Cleaning your source tree with Cargo
        2. Creating documentation using Cargo
          1. rustdoc versus Cargo
        3. Using Cargo to help with your unit testing
          1. Assert yourself!
        4. Is there anything Cargo can't do?
    3. Summary
  3. Variables
    1. Variable mutability
      1. Creating a variable
        1. How can we tell the compiler that we want x to be an int?
      2. Defining other variable types
        1. Float
        2. Signed and unsigned integers
        3. Const and static
      3. Defining the variable value before use
        1. Strings
      4. How Rust uses memory
        1. Back to Strings
      5. String slices
        1. What's with the warnings?
        2. Using the format! macro
        3. Building a string
        4. Code review
      6. Casting
      7. String methods
      8. Generics and arrays
      9. Arrays
        1. Array performance
        2. Vectors
        3. Creating a vector with an initial size
        4. Creating a vector via an iterator
        5. Adding and removing from the vector
      10. Manipulating an array or vector via slices
      11. Passing values around
      12. Passing by value
      13. Passing by reference
        1. The reference type
        2. A practical example
    2. Summary
  4. Input and Output
    1. Functions and methods in Rust
      1. The difference between println! and println
    2. Introduction to the standard library
      1. The libraries
      2. Controlling the output formatting
        1. Positioning the output
        2. Named parameters
        3. Specifying the argument types
        4. Formatting traits
        5. Formatting parameters
      3. Getting information in
    3. Command-line arguments
    4. Handling files
      1. Reading from a file
        1. Loading a file
        2. Writing a file
        3. The use of expect
      2. XML and Rust
        1. Reading a file
        2. Writing a file
    5. Summary
  5. Conditions, Recursion, and Loops
    1. Loops
      1. The for loop
        1. Using enumerate
        2. The _ parameter
        3. The simple loop
        4. The while condition
        5. Prematurely terminating a loop
        6. Using loop labels
      2. Recursive functions
        1. What is the difference between having and not having a semicolon?
    2. Summary
  6. Remember, Remember
    1. Let's start at the beginning
      1. The stack frame
        1. What is meant by the stack?
    2. Let's consider the heap
      1. Deallocation
    3. What about functions with arguments?
    4. Static memory allocation
      1. Garbage collecting time and ownership
        1. An owned pointer example
      2. Comparison to C
      3. Let's revisit some old code
      4. Let's not race ahead!
        1. Stop the race...
    5. Summary
  7. Creating Your Own Rust Applications
    1. Project 1 - let's start with some math
      1. Requirements
        1. Supplied data
        2. Application output
    2. Project 2 - some text manipulation
      1. Requirements
        1. Code notes
    3. Project 3 – area and volume
      1. Shape types
        1. Volume or area
        2. User-defined shape
      2. Formulae for calculations
      3. Testing criteria
      4. Auto-documentation
        1. Using regular expressions (regex)
      5. Input and output
    4. Project 4 – memory
      1. Bitwise rotation
        1. Rotation caveat
      2. Output
    5. Summary
  8. Matching and Structures
    1. Structs 101
      1. Variables, variables everywhere
        1. The structure of a struct
        2. Smaller is better
      2. Accessing a struct
      3. Defining the child structures
    2. Multi-file version
      1. Private versus public fields
      2. Structs 102
      3. Tuples
        1. Using a tuple to define a variable
          1. Tuple indexing
        2. Destructuring with let
      4. Tuple structs – the hybrid of two
        1. The single element tuple struct
        2. Back to the unit-like struct
    3. Enumerations
      1. Accessing enumeration members
        1. The two questions you should be asking
    4. Patterns and matching
      1. Matching
        1. Let's really make the function simple
        2. Using match with an enum
        3. Ignoring a parameter with match
      2. Fall through patterns
        1. Ranges
        2. Creating a binding within a match pattern
        3. Let's add an if into the mix
        4. Using match with a compound type
      3. And back to if let
    5. Summary
  9. The Rust Application Lifetime
    1. What are they?
      1. Ownership
      2. Borrowing
      3. Lifetime
    2. Ownership in Rust
      1. Abstractions
      2. Ownership – from the beginning
        1. Variable binding
      3. Stack and heap variables
        1. Why is this important?
      4. The Copy trait
      5. Borrowing in Rust
        1. Borrow immutability
        2. Mutable borrows
      6. The Rust borrowing rules
      7. Fixing the problem
        1. Think about the scope
      8. It's all for your own good
    3. The lifetime
      1. The mythical bank account
      2. The lifetime variable - '
      3. Lifetime of other types
        1. Lifetime within an struct
        2. Multiple lifetimes
        3. Always consider the scope
        4. 'struct
      4. Input and output lifetimes
        1. Input only
        2. Output only
        3. Input and output
    4. Summary
  10. Introducing Generics, Impl, and Traits
    1. Generics 101
      1. Understanding the error
      2. A generic problem
        1. The unsafe directive
        2. The whole #!
    2. Traits and Impl
      1. Impl
      2. The impl lifetime
      3. And back to traits we go...
      4. A simple crate example
    3. Traits and generics
      1. Defining the impl for specific types
      2. Using where
      3. Making it work
    4. Something you may have noticed
      1. Generics - a small aside
        1. So what does happen?
    5. Back to the where version
      1. Try to compile
    6. Trait bounds
    7. Can we reduce the amount of code further?
      1. Can the default method be overridden?
    8. Rounding off traits
      1. Inheritance
      2. Deriving
    9. Trait objects
      1. Let's create a sample test setup
      2. Let's see dynamic dispatch
      3. Keeping your object safe
    10. Summary
  11. Creating Your Own Crate
    1. What exactly is a crate?
      1. Looking at modules
        1. I can see a problem with this analogy
      2. Back to our math library
        1. Using a useful name
      3. Let's create!
        1. Creating top-level modules
      4. The multifile module
        1. What about submodules?
        2. The mod.rs file
      5. Let's add some code
    2. Beware of double name scopes
      1. Adding unit tests to the library
        1. Making something public
      2. Let's give our crate a quick run out
        1. External dependencies
      3. Changing the scope
        1. Altering the crate name
        2. Optimizing your use statements
          1. The use-everything approach
          2. The you-decide approach
          3. The use-me approach
          4. The use-me-but-call-me-something-else approach
          5. The use-glob approach
          6. The use-glob-self approach
    3. Summary
  12. Concurrency in Rust
    1. A bit of a story
      1. What was that all about?
      2. Send
      3. Sync
        1. When is an immutable variable not an immutable variable?
        2. And it's obviously mutable, it has mut in the definition
        3. Interior mutability
      4. Back to sync
      5. A beginner's guide to threading in Rust
        1. An easy approach to thinking about how threads work.
        2. Joining threads
      6. Closures
        1. Closures aren't all they first appear to be
        2. Closures as function arguments
        3. Closures with explicit lifetimes – a special case
        4. Returning a closure
        5. What is the move parameter?
      7. Back to threading
      8. Ownership has its advantages
        1. The reference counter
        2. Problem solved – use Mutex
        3. Why do we put the thread to sleep?
        4. Thread synchronization
      9. Thread panics
    2. Summary
  13. Now It's Your Turn!
    1. Task 1 – cleaning the code (part 1)
      1. The problems with each option
        1. The String option
        2. The struct option
        3. The task
    2. Task 2 – cleaning the code (part 2)
      1. The task
    3. Task 3 – extending the crate (part 1)
      1. The task
    4. Task 4 – extending the crate (part 2)
    5. Summary
  14. The Standard Library
    1. Chapter format
    2. What is the standard library?
      1. The standard modules (overview)
      2. Primitive types (overview)
      3. Macros (overview)
      4. Prelude
    3. The standard modules
      1. std::Any
      2. std::ascii
      3. std::borrow
      4. std::boxed
      5. std::cell
      6. std::char
      7. std::clone
      8. std::cmp
      9. std::collections
      10. std::convert
      11. std::default
      12. std:env
      13. std:error
      14. std::f32
      15. std::f64
      16. std:ffi
      17. std::fmt
      18. std::fs
      19. std::hash
      20. std::i8
      21. std::i16
      22. std::i32
      23. std::i64
      24. std::io
      25. std::isize
      26. std::iter
      27. std::marker
      28. std::mem
      29. std:net
      30. std::num
      31. std::os
      32. std::panic
      33. std::path
      34. std::process
      35. std::ptr
      36. std::slice
      37. std::str
      38. std::string
      39. std::sync
      40. std::thread
      41. std::time
      42. std::u8
      43. std::u16
      44. std::u32
      45. std::u64
      46. std::usize
      47. std::vec
    4. Summary
  15. Foreign Function Interfaces
    1. Introducing our simple library
    2. The three-step program
      1. Including the dependency
      2. Creating the code
        1. What's the [link(name="")] for?
        2. What's the big deal? That was simple enough!
      3. Let's extend things a bit
        1. What happens if the types don't match?
      4. Can we make things safer?
        1. Wrappers
        2. A practical example
        3. Accessing global variables
      5. Cleaning up after yourself
        1. Drop it!
      6. Monitoring an external process within an FFI
        1. Targeting synchronous callbacks
      7. Targeting a Rust object
      8. Calling Rust from another language
      9. Dealing with the unknown
        1. C structs
    3. Summary

Product information

  • Title: Learning Rust
  • Author(s): Paul Johnson, Vesa Kaihlavirta
  • Release date: November 2017
  • Publisher(s): Packt Publishing
  • ISBN: 9781785884306