O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Rust Programming By Example

Book Description

Discover the world of Rust programming through real-world examples

About This Book

  • Implement various features of Rust to build blazingly fast applications
  • Learn to build GUI applications using Gtk-rs
  • Explore the multi-threading aspect of Rust to tackle problems in concurrency and in distributed environments

Who This Book Is For

This book is for software developers interested in system level and application programming who are looking for a quick entry into using Rust and understanding the core features of the Rust Programming. It's assumed that you have a basic understanding of Java, C#, Ruby, Python, or JavaScript.

What You Will Learn

  • Compile and run the Rust projects using the Cargo-Rust Package manager
  • Use Rust-SDL features such as the event loop, windows, infinite loops, pattern matching, and more
  • Create a graphical interface using Gtk-rs and Rust-SDL
  • Incorporate concurrency mechanism and multi-threading along with thread safety and locks
  • Implement the FTP protocol using an Asynchronous I/O stack with the Tokio library

In Detail

Rust is an open source, safe, concurrent, practical language created by Mozilla. It runs blazingly fast, prevents segfaults, and guarantees safety. This book gets you started with essential software development by guiding you through the different aspects of Rust programming. With this approach, you can bridge the gap between learning and implementing immediately.

Beginning with an introduction to Rust, you'll learn the basic aspects such as its syntax, data types, functions, generics, control flows, and more. After this, you'll jump straight into building your first project, a Tetris game. Next you'll build a graphical music player and work with fast, reliable networking software using Tokio, the scalable and productive asynchronous IO Rust library.

Over the course of this book, you'll explore various features of Rust Programming including its SDL features, event loop, File I/O, and the famous GTK+ widget toolkit. Through these projects, you'll see how well Rust performs in terms of concurrency—including parallelism, reliability, improved performance, generics, macros, and thread safety. We'll also cover some asynchronous and reactive programming aspects of Rust.

By the end of the book, you'll be comfortable building various real-world applications in Rust.

Style and approach

This comprehensive guide uses practical examples to implement various RUST programming features.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Table of Contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  2. Basics of Rust
    1. Getting to know Rust
      1. Installing Rust
        1. Windows
        2. Linux/Mac 
        3. Test your installation
    2. Documentation and reference
    3. Main function
      1. Variables
    4. Built-in data types
      1. Integer types
      2. Floating-point types
      3. Boolean type
      4. Character type
    5. Control flow
      1. Writing a condition
      2. Creating while loops
    6. Creating functions
    7. Creating structures
    8. References
      1. Clone types
      2. Copy types
      3. Mutable references
    9. Methods
      1. Constructors
    10. Tuples
    11. Enumerations
    12. Pattern matching
      1. Irrefutable patterns
    13. Traits
      1. Default methods
      2. Associated types
      3. Rules
    14. Generics
      1. The Option type
    15. Arrays
      1. Slices
      2. For loops
    16. Macros
      1. Multiple pattern rules
      2. Repetitions
        1. Optional quantifier
    17. Summary
  3. Starting with SDL
    1. Understanding Rust crates
    2. Installing SDL2
      1. Installing SDL2 on Linux
      2. Installing SDL2 on Mac
      3. Installing SDL2 on Windows
        1. Windows with Build Script
        2. Windows (MinGW)
        3. Windows (MSVC)
    3. Setting up your Rust project
      1. Cargo and crates.io
      2. The docs.rs documentation
        1. Back to our Cargo.toml file
    4. Rust's modules
    5. Tetris
    6. Creating a window
    7. Drawing
      1. Playing with Options
      2. Solution
      3. Loading images
        1. Installing SDL2_image on Mac
        2. Installing SDL2_image on Linux
        3. Installing SDL2_image on Windows
      4. Playing with features
      5. Playing with images
    8. Handling files
      1. Saving/loading high scores
      2. Iterators
      3. Reading formatted data from files
    9. Summary
  4. Events and Basic Game Mechanisms
    1. Writing Tetris
      1. Tetrimino
      2. Creating tetriminos
      3. Generating a tetrimino
        1. Rotating a tetrimino
      4. Tetris struct
      5. Interacting with the game map
      6. SDL events
      7. Score, level, lines sent
        1. Levels and lines sent
        2. Highscores loading/overwriting
    2. Summary
  5. Adding All Game Mechanisms
    1. Getting started with game mechanisms
      1. Rendering UI
        1. Rendering initialization
        2. Rendering
      2. Playing with fonts
        1. Install on OS X
        2. Install on Linux
        3. Other system/package manager
      3. Loading font
    2. Summary
  6. Creating a Music Player
    1. Installing the prerequisite
      1. Installing GTK+ on Linux
      2. Installing GTK+ on Mac
      3. Installing GTK+ on Windows
    2. Creating your first window
      1. Closure
      2. Preventing the default behavior of an event
    3. Creating a toolbar
      1. Stock item
    4. Improving the organization of the application
    5. Adding tool button events
      1. Lifetime
      2. Ownership
    6. Containers
      1. Types of containers
      2. The Box container
    7. Adding a playlist
      1. The MVC pattern
    8. Opening MP3 files
      1. Reference-counting pointer
      2. ID3— MP3 metadata
      3. Opening files with a file dialog
      4. Deleting a song
      5. Displaying the cover when playing a song
    9. Summary
  7. Implementing the Engine of the Music Player
    1. Installing the dependencies
      1. Installing dependencies on Linux
      2. Installing dependencies on Mac
      3. Installing dependencies on Windows
    2. Decoding MP3 files
      1. Adding dependencies
      2. Implementing an MP3 decoder
      3. Getting the frame samples
    3. Playing music
      1. Event loop
        1. Atomic reference counting
        2. Mutual exclusion
        3. Send trait
        4. Sync trait
        5. Lock-free data structures
      2. Playing music
        1. Mutex guard
        2. RAII
      3. Using the music player
    4. Pausing and resuming the song
      1. Interior mutability
    5. Showing the progression of the song
    6. Improving CPU usage
      1. Condition variable
    7. Showing the song's current time
    8. Loading and saving the playlist
      1. Saving a playlist
      2. Loading a playlist
    9. Using gstreamer for playback
    10. Summary
  8. Music Player in a More Rusty Way with Relm
    1. Reasons to use relm instead of gtk-rs directly
      1. State mutation
      2. Asynchronous user interface
      3. Creating custom widgets
    2. Creating a window with relm
      1. Installing Rust nightly
    3. Widget
      1. Model
      2. Messages
      3. View
        1. Properties
        2. Events
        3. Code generation
      4. Update function
    4. Adding child widgets
      1. One-way data binding
      2. Post-initialization of the view
      3. Dialogs
      4. Other methods
    5. Playlist
      1. Model parameter
    6. Adding a relm widget
    7. Communicating between widgets
      1. Communicating with the same widget
      2. Emit
      3. With different widgets
        1. Handle messages from a relm widget
        2. Syntax sugar to send a message to another relm widget
    8. Playing music
    9. Computing the song duration
    10. Using relm on stable Rust
    11. Relm widgets data binding
    12. Summary
  9. Understanding FTP
    1. File transfer protocol
      1. Introduction to FTP
      2. Implementing simple chunks of commands
        1. Starting with basics
      3. Commands implementation
        1. Implementing the SYST command
        2. Implementing the USER command
        3. Implementing the NOOP command
        4. Implementing the PWD command
        5. Implementing the TYPE command
        6. Implementing the LIST command
          1. Implementing the PASV command
          2. Back to the LIST command
        7. Implementing the CWD command
        8. Implementing the CDUP command
        9. Full implementation of the LIST command
        10. Implementing the MKD command
        11. Implementing the RMD command
      4. Testing it
    2. Summary
  10. Implementing an Asynchronous FTP Server
    1. Advantages of asynchronous IO
    2. Disadvantages of asynchronous IO
    3. Creating the new project
    4. Using Tokio
      1. Tokio event loop
    5. Using futures
    6. Handling errors
      1. Unwrapping
      2. Custom error type
        1. Displaying the error
        2. Composing error types
        3. The ? operator, revisited
    7. Starting the Tokio event loop
    8. Starting the server
      1. Handling clients
      2. Handling commands
      3. FTP codec
        1. Decoding FTP commands
        2. Encoding FTP commands
    9. Handling commands
    10. Managing the current working directory
      1. Printing the current directory
      2. Changing the current directory
    11. Setting the transfer type
    12. Entering passive mode
      1. Bytes codec
        1. Decoding data bytes
        2. Encoding data bytes
    13. Quitting
    14. Creating directories
    15. Removing directories
    16. Summary
  11. Implementing Asynchronous File Transfer
    1. Listing files
    2. Downloading a file
    3. Uploading files
    4. Going further!
      1. Configuration
      2. Securing the config.toml access
    5. Unit tests
      1. Backtraces
      2. Testing failures
      3. Ignoring tests
    6. Integration tests
      1. Teardown
      2. Print output to stdout
    7. Documentation
      1. Documenting a crate
      2. Documenting a module
      3. Headers
      4. Code blocks
      5. Documenting an enumeration (or any type with public fields)
      6. Generating the documentation
      7. Warning about public items without documentation
      8. Hiding items from the documentation
    8. Documentation tests
      1. Tags
        1. ignore
        2. compile_fail
        3. no_run
        4. should_panic
        5. Combining flags?
      2. About the doc blocks themselves
        1. Hiding code blocks lines
    9. Fuzzing tests
    10. Summary
  12. Rust Best Practices
    1. Rust best practices
      1. Slices
      2. API tips and improvements
        1.  Explaining the Some function
        2.  Using the Path function
      3. Usage tips
        1. Builder pattern
          1. Playing with mutable borrows
          2. Playing with moves
      4. Code readability
        1. Big number formatting
        2. Specifying types
        3. Matching
    2. Summary
  13. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think