Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Rust

You're reading from   Learning Rust A comprehensive guide to writing Rust applications

Arrow left icon
Product type Paperback
Published in Nov 2017
Publisher Packt
ISBN-13 9781785884306
Length 308 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Vesa Kaihlavirta Vesa Kaihlavirta
Author Profile Icon Vesa Kaihlavirta
Vesa Kaihlavirta
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Introducing and Installing Rust FREE CHAPTER 2. Variables 3. Input and Output 4. Conditions, Recursion, and Loops 5. Remember, Remember 6. Creating Your Own Rust Applications 7. Matching and Structures 8. The Rust Application Lifetime 9. Introducing Generics, Impl, and Traits 10. Creating Your Own Crate 11. Concurrency in Rust 12. Now It's Your Turn! 13. The Standard Library 14. Foreign Function Interfaces

Your first Rust project

Your first Rust project is not going to be particularly amazing. If anything, it's going to serve four purposes:

  • Showing the structure of a Rust project
  • Showing how to create a project by hand
  • Showing how to create a project using the Rust Cargo script
  • Compiling and executing the program

Structure of a Rust project

A Rust project (irrespective of the platform you are developing on) will have the following structure:

The preceding screenshot shows the structure of the simplest Rust project, and as such can be replicated using the following commands:

OS X/Linux

Windows (from the command prompt)

mkdir firstproject cd firstproject touch Cargo.toml mkdir src cd src touch main.rs
md firstproject cd firstproject md src echo $null >> Cargo.toml cd src echo $null >> main.rs
The echo $null >> filename command creates an empty file without the need to start Notepad; save the file and exit.

The Cargo.toml file is the Rust equivalent of a Makefile. When the .toml file is created by hand, it should be edited to contain something like this:

The structure of a Rust project can expand to include documentation as well as the build structure, as follows:

Automating things

While there is nothing wrong with creating a Rust project by hand, Rust does come with a very handy utility called Cargo. Cargo can be used not only to automate the setting up of a project, but also to compile and execute Rust code. Cargo can be used to create the parts required for a library instead of an executable, and can also generate application documentation.

Creating a binary package using Cargo

As with any other script, Cargo works (by default) on the current working directory. (For example, while writing this chapter, my working directory for the example code is ~/Developer/Rust/chapter0 on the Mac and Linux boxes, and J:\Developer\Rust\Chapter0 on the Windows 10 machine.)

In its simplest form, Cargo can generate the correct file structure like this:

cargo new demo_app_name -bin 

The preceding command tells Cargo to create a new structure called demo_app_name, and that it is to be a binary. If you remove -bin, it creates a structure called, which is going to be a library (or more accurately, something other than a binary).

If you don't wish to use the root (say you want to create a library within your binary framework), then instead of demo_app_name, you append the structure before the name relating to your working directory.

In the small example I gave earlier, if I wanted to create a library within my binary structure, I would use the following:

cargo new app_name/mylib  

That will create a structure like this:

The Cargo.toml file requires no editing (at this stage), as it contains the information we had to enter manually when we created the project by hand.

Cargo has a number of directory separator translators. This means that the preceding example can be used on OS X, Linux, and Windows without an issue; Cargo has converted the / to \ for Windows.

Using Cargo to build and run an application

As we are all able to create directory structures, Cargo is then able to build and execute our source code.

If you look at the source code that comes with this chapter, you will find a directory called app_name. To build this package using Cargo, type the following from a Terminal (or command on Windows) window:

cd app_name 
cargo build app_name  

This will build the source code; finally you will be informed that the compilation has been successful:

Next, we can use Cargo to execute the binary as follows:

cargo run

If everything has worked, you will see something like the following:

As with any sort of utility, it's possible to "daisy-chain" the build and execution into one line, as follows:

cargo build; cargo run  
You may be wondering why the first operation performed was to move into the application structure rather than just type cargo build. This is because Cargo is looking for the Cargo.toml file (remember, this acts as a build script).

Cleaning your source tree with Cargo

When the Rust compiler compiles the source files, it generates something known as an object file. The object file takes the source file (which we can read and understand) and compiles this into a form that can be joined with other libraries to create a binary.

This is a good idea, as it cuts down on compilation time; if a source file has not been changed, there is no need to recompile the file, as the object file will be the same.

Sometimes, the object file becomes out of date, or code in another object file causes a panic due to conflicts. In this case, it is not uncommon to "clean" the build. This removes the object files, and the compiler then has to recompile all the source files.

Also, it should always be performed prior to creating a release build.

The standard Unix make program performs this with the clean command (make clean). Cargo performs the clean operation in a way similar to the make utility in Unix:

cargo clean  

A comparison of the directories shows what happens when using the preceding Cargo command:

The entire target directory structure has simply been removed (the preceding screenshot was from a Mac, hence the dSYM and plist files. These do not exist on Linux and Windows).

Creating documentation using Cargo

As with other languages, Rust is able to create documentation based on meta tags with the source files. Take the following example:

fn main() 
{ 
   print_multiply(4, 5); 
} 
 
/// A simple function example 
/// 
/// # Examples 
/// 
/// ``` 
/// print_multiply(3, 5); 
///  
/// ``` 
 
fn print_multiply(x: i32, y: i32) 
{ 
   println!("x * y = {}", x * y); 
} 

The comments preceded by /// will be converted into documentation.

The documentation can be created in one of two ways: via Cargo or by using the rustdoc program.

rustdoc versus Cargo

As with the other operations provided by Cargo, when documentation is created, it acts as a wrapper for rustdoc. The only difference is that with rustdoc you have to specify the directory that the source file sits in. Cargo acts dumb in this case, and creates the documentation for all source files.

In its simplest form, the rustdoc command is used as follows:

cargo doc
rustdoc src/main.rs  

Cargo does have the advantage of creating the doc structure within the root folder, whereas rustdoc creates the structure within the target (which is removed with cargo clean).

Using Cargo to help with your unit testing

Hopefully, unit testing is not something you will be unfamiliar with. A unit test is a test that operates on a specific function or method rather than an entire class or namespace. It ensures that the function operates correctly on the data it is presented with.

Unit tests within Rust are very simple to create (two examples are given in the assert_unittest and unittest directories). The following has been taken from the unittest example:

fn main() { 
    println!("Tests have not been compiled, use rustc --test instead (or cargo test)"); 
} 
 
#[test] 
fn multiply_test() 
{ 
   if 2 * 3 == 5 
   { 
      println!("The multiply worked"); 
   } 
} 

When this is built and executed, you may be surprised by the following result:

The reason why this unit test has passed despite 2 x 3 not being 5 is because the unit test is not testing the result of the operation, but that the operation itself is working. It is very important that this distinction is understood from an early stage to prevent confusion later.

We have hit a limitation of unit testing: if we are not testing the data but the operation, how can we know that the result itself is correct?

Assert yourself!

Unit testing provides the developer with a number of methods called assertion methods:

#[test] 
fn multiply() 
{ 
   assert_eq!(5, 2 * 3); 
} 

In the preceding code snippet, we use the assert_eq! (assert equal) macro. The first argument is the answer expected, and the second argument is what is being tested. If 2 * 3 = 5, then the assertion is true and passes the unit test.

Is there anything Cargo can't do?

For a Rust developer, Cargo is an amazing utility. In addition to these common facilities, it also has other commands, which are listed in the table that follows. All commands follow this form:

cargo <command> <opts>  

Command

What it does

fetch

This command fetches the dependencies of a package from the network. If a lockfile is available, this command will ensure that all of the Git dependencies and/or registry dependencies are downloaded and locally available. The network is never called after a cargo fetch unless the lockfile changes.

If the lockfile is not available, then this is the equivalent of cargo generate-lockfile. A lockfile is generated and all the dependencies are also updated.

generate-lockfile

This command generates the lockfile for a project. The lockfile is typically generated when cargo build is issued (you will see it as Cargo.lockfile in the directory structure).

git-checkout

This command checks out a Git repository. You will need to use it in the following form:

cargo git-checkout -url=URL        
locate-project

This command locates a package.

login

This command saves an API token from the registry locally. The call is in the following form:

cargo login -host=HOST   token        
owner

This command manages the owners of a crate on the registry. This allows the ownership of a crate (a crate is a Rust library) to be altered (--add LOGIN or -remove LOGIN) as well as adding tokens to the crate.

This command will modify the owners for a package on the specified registry (or the default). Note that the owners of a package can upload new versions, yank old versions, and also modify the set of owners, so be cautious!

package

This command assembles the local package into a distributable tarball.

pkgid

This command prints a fully qualified package specification.

publish

This command uploads a package to the registry.

read-manifest

This command reads the manifest file (.toml).

rustc

This command compiles the complete package.

The specified target for the current package will be compiled along with all of its dependencies. The specified options will all be passed to the final compiler invocation, not any of the dependencies. Note that the compiler will still unconditionally receive arguments such as -L, --extern, and --crate-type, and the specified options will simply be added to the compiler invocation.

This command requires that only one target is being compiled. If more than one target is available for the current package, the filters --lib, --bin, and so on—must be used to select which target is compiled.

search

This command searches for packages at https://crates.io/.

update

This command updates dependencies as recorded in the local lockfile.

Typical options are:

  • --package SPEC (package to update)
  • --aggressive (forcibly update all dependencies of <name> as well)
  • --precise PRECISE (update a single dependency to exactly PRECISE)

This command requires that a Cargo.lock file already exists as generated by cargo build or related commands.

If a package spec name (SPEC) is given, then a conservative update of the lockfile will be performed. This means that only the dependency specified by SPEC will be updated. Its transitive dependencies will be updated only if SPEC cannot be updated without updating the dependencies. All other dependencies will remain locked at their currently recorded versions.

If PRECISE is specified, then --aggressive must not also be specified. The argument PRECISE is a string representing a precise revision that the package being updated should be updated to. For example, if the package comes from a Git repository, then PRECISE would be the exact revision that the repository should be updated to.

If SPEC is not given, then all the dependencies will be re-resolved and updated.

verify-project

This command ensures that the project is correctly created.

version

This command shows the version of Cargo.

yank

This command removes a pushed crate from the index.

The yank command removes a previously pushed crate version from the server's index. This command does not delete any data, and the crate will still be available for download via the registry's download link.

Note that existing crates locked to a yanked version will still be able to download the yanked version to use it. Cargo will, however, not allow any new crates to be locked to any yanked version.

 

As you can now appreciate, the Cargo utility script is extremely powerful and flexible.

You have been reading a chapter from
Learning Rust
Published in: Nov 2017
Publisher: Packt
ISBN-13: 9781785884306
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