Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Rust Programming By Example
Rust Programming By Example

Rust Programming By Example: Enter the world of Rust by building engaging, concurrent, reactive, and robust applications

eBook
£29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £9.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Rust Programming By Example

Chapter 2. Starting with SDL

Beforestarting to write the Tetris, a few things remain to be talked about, such as crates, which we'll be using a lot (and you'll be using a lot as well once you're rusting on your own!). Let's start withcrates!

Understanding Rust crates


In Rust, packages (both binaries and libraries) are named crates. You can find a lot of them on crates.io. Today, we'll use the SDL2 crate in order to make our tetris, but before even thinking about this, we need to install the SDL2library that is used by the SDL2 crate!

Installing SDL2


Before going any further, we need to install the SDL library.

Installing SDL2 on Linux

Depending on your package management tool, run the following to install SDL2 on Linux:

apt package mananger:

$ sudo apt-get install libsdl2-dev

dnf package manager:

$ sudo dnf install SDL2-devel

yum package manager:

$ yum install SDL2-devel

Once done, your SDL2 installation is ready!

Installing SDL2 on Mac

To install SDL2 on Mac, Simply run the following:

$ brew install sdl2

You're good to go!

Installing SDL2 on Windows

All these installation instructions come directly from the Rust SDL2 crate.

Windows with Build Script

A few steps will be required in order to make all of it work. Follow the guide!

  1. Download the mingw and msvc development libraries from http://www.libsdl.org/ (SDL2-devel-2.0.x-mingw.tar.gz and SDL2-devel-2.0.x-VC.zip).
  2. Unpack to folders of your choice. (You can delete it afterward.)
  3. Create the following folder structure in the same folder as your Cargo.toml:
        gnu-mingw\dll\32
       ...

Setting up your Rust project


The Rust package manager, cargo, allows us to create a new project very easily with just one command, cargo new. Let's run it as follow:

  cargo new tetris --bin

You should have a new folder tetris containing the following:

     tetris/
     |
     |- Cargo.toml
     |- src/
         |
         |- main.rs

Note that if you ran cargo new without the --bin flag, then you will have a lib.rs file instead of main.rs.

Now write this into your Cargo.toml file:

    [package]
    name = "tetris"
    version = "0.0.1"

    [dependencies]
    sdl2 = "0.30.0"

Here, we declare that our project's name is tetris, its version is 0.0.1 (it isn't really important at the moment), and that it has a dependency on the sdl2 crate.

For the versioning, Cargo follows SemVer (Semantic Versioning). It works as follows:

[major].[minor].[path]

So here's exactly what every part means:

  • Update the [major] number version when you make incompatible API changes
  • Update the [minor] number version when adding...

Rust's modules


Before going any further, we need to talk about how file hierarchy works in Rust through its modules.

The first thing to know is that files and folders are handled as modules in Rust. Consider the following:

|- src/
    |
    |- main.rs
    |- another_file.rs

If you want to declare that a module is in the another_file.rs file, you'll need to add to your main.rs file:

    mod another_file;

You will now have access to everything contained in another_file.rs (as long as it's public).

Another thing to know: you can only declare modules whose files are on the same level as your current module/file. Here's a short example to sum this up:

|- src/
    |
    |- main.rs
    |- subfolder/
        |- another_file.rs

If you try to declare a module referring to another_file.rs directly into main.rs, as shown preceding, it'll fail because there are no another_file.rs in src/. In this case, you'll need to do three things:

  1. Add a mod.rs file into the subfolder folder.
  2. Declare another_file into mod.rs...

Tetris


Okay, we're now ready to start writing down our tetris!

First, let's fulfill our main.rs file in order to check whether everything is working as expected:

    extern crate sdl2;

    use sdl2::pixels::Color;
    use sdl2::event::Event;
    use sdl2::keyboard::Keycode;
    use std::time::Duration;
    use std::thread::sleep;

    pub fn main() {
      let sdl_context = sdl2::init().expect("SDL initialization   
      failed");
      let video_subsystem = sdl_context.video().expect("Couldn't get 
       SDL video subsystem");

      let window = video_subsystem.window("rust-sdl2 demo: Video", 800,
            600)
        .position_centered()
        .opengl()
        .build()
        .expect("Failed to create window");

      let mut canvas = window.into_canvas().build().expect("Failed to
        convert window into canvas");

      canvas.set_draw_color(Color::RGB(255, 0, 0));
      canvas.clear();
      canvas.present();
      let mut event_pump = sdl_context.event_pump().expect("Failed...

Creating a window


The previous example created a window and drew into it. Now let's see how it did that!

Before going any further, we need to import the SDL2 crate, as follows:

    extern crate sdl2;

With this, we now have access to everything it contains.

Now that we've imported sdl2, we need to initialize an SDL context:

    let sdl_context = sdl2::init().expect("SDL initialization failed");

Once done, we need to get the video subsystem:

    let video_subsystem = sdl_context.video().expect("Couldn't get SDL 
      video subsystem");

We can now create the window:

    let window = video_subsystem.window("Tetris", 800, 600)
                            .position_centered()
                            .opengl()
                            .build()
                            .expect("Failed to create window");

A few notes on these methods:

  • The parameters for the window method are title, width, height
  • .position_centered() gets the window in the middle of the screen
  • .opengl() makes the SDL use opengl to render...

Drawing


We now have a working window; it'd be nice to draw into it. First, we need to get the window's canvas before starting the main loop:

    let mut canvas = window.into_canvas()
                       .target_texture()
                       .present_vsync()
                       .build()
                       .expect("Couldn't get window's canvas");

A few explanations for the preceding code:

  • into_canvas transforms the window into a canvas so that we can manipulate it more easily
  • target_texture activates texture rendering support
  • present_vsync enables the v-sync (also known as vertical-synchronization) limit
  • build creates the canvas by applying all previously set parameters

Then we'll create a texture that we'll paste onto the window's canvas. First, let's get the texture creator, but before that, add this include at the top of the file:

    use sdl2::render::{Canvas, Texture, TextureCreator};

Now we can get the texture creator:

    let texture_creator: TextureCreator<_> = canvas.texture_creator...

Handling files


Let's start with the basics. First, let's open and write into a file:

    use std::fs::File;
    use std::io::{self, Write};

    fn write_into_file(content: &str, file_name: &str) -> io::Result<()> {
      let mut f = File::create(file_name)?;
      f.write_all(content.as_bytes())
    }

Now let's explain this code:

    use std::fs::File;

Nothing fancy, we just import the File type:

   use std::io::{self, Write};

This set of imports is more interesting: we import the io module (self) and the Write trait. For the second, if we didn't import it, we wouldn't be able to use the write_all method (because you need to import a trait to use its methods):

   fn write_into_file(content: &str, file_name: &str) -> io::Result<()> {

We declared a function named write_into_file that takes a filename and the content you want to write into the file as arguments. (Note that the file will be overwritten by this content!) It returns an io::Result type. It is an alias...

Summary


In this chapter, we saw a lot of important things like how to use Cargo (through the Cargo.toml file), how to import new crates into a project, thanks to Cargo, and the basics for Rust modules handling. We even covered how to use iterators and read and write files, SDL2 basics like how to create a window and fill it with colors, and loading/creating new textures and images (thanks to the SDL2-image library!).

In Chapter 3, Events and Basic Game Mechanisms, we'll start the implementation of the tetris game, so be sure to master everything explained in this chapter before starting the next one!

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • 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

Description

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.

Who is this book 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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 11, 2018
Length: 454 pages
Edition : 1st
Language : English
ISBN-13 : 9781788470308
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 11, 2018
Length: 454 pages
Edition : 1st
Language : English
ISBN-13 : 9781788470308
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£9.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£99.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£139.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 110.97
Rust Programming By Example
£36.99
Network Programming with Rust
£36.99
Rust Essentials
£36.99
Total £ 110.97 Stars icon
Visually different images

Table of Contents

11 Chapters
Basics of Rust Chevron down icon Chevron up icon
Starting with SDL Chevron down icon Chevron up icon
Events and Basic Game Mechanisms Chevron down icon Chevron up icon
Adding All Game Mechanisms Chevron down icon Chevron up icon
Creating a Music Player Chevron down icon Chevron up icon
Implementing the Engine of the Music Player Chevron down icon Chevron up icon
Music Player in a More Rusty Way with Relm Chevron down icon Chevron up icon
Understanding FTP Chevron down icon Chevron up icon
Implementing an Asynchronous FTP Server Chevron down icon Chevron up icon
Implementing Asynchronous File Transfer Chevron down icon Chevron up icon
Rust Best Practices Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(4 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 50%
1 star 0%
Donald A. Newell Jr. Mar 14, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good refernce book for beginners
Amazon Verified review Amazon
Emerson Chalegre Nov 15, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good!
Amazon Verified review Amazon
Roshan Lenagala Aug 06, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Tried this book because it's easier to learn a new language while doing a project. The explanations are not that great. Some of the logic in the examples are not explained enough.
Amazon Verified review Amazon
Blurred May 26, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Just getting started with this book and I'm getting hung up on fixing broken examples in the book before even finishing chapter 2. Not sure how much of it is due to being out of date, but this is a fine example for the future of technical books: they should be published and accessible online. Technology is changing faster now than ever and will keep changing. Books like these simply aren't able to keep up.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.