Book Image

Rust Essentials

By : Ivo Balbaert
Book Image

Rust Essentials

By: Ivo Balbaert

Overview of this book

<p>Starting by comparing Rust with other programming languages, this book will show you where and how to use Rust. It will discuss primitive types along with variables and their scope, binding and casting, simple functions, and ways to control execution flow in a program.</p> <p>Next, the book covers flexible arrays, vectors, tuples, enums, and structs. You will then generalize the code with higher-order functions and generics applying it to closures, iterators, consumers, and so on. Memory safety is ensured by the compiler by using references, pointers, boxes, reference counting, and atomic reference counting. You will learn how to build macros and crates and discover concurrency for multicore execution.</p> <p>By the end of this book, you will have successfully migrated to using Rust and will be able to use it as your main programming language.</p>
Table of Contents (17 chapters)
Rust Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Testing


We can prefix a function with the #[test] attribute to indicate that it is part of the unit tests for our application or library. We can then compile with rustc --test program.rs. This will replace the main() function with a test runner and show the result from the functions marked with #[test]. Have a look at the following code snippet:

   // from Chapter 3/code/attributes_testing.rs
fn main() {
println!("No tests are compiled,compile with rustc --test! ");
}

#[test]
fn arithmetic() {
  if 2 + 3 == 5 {
    println!("You can calculate!");
  }
}

Test functions, such as arithmetic() in the example, are black boxes; they have no arguments or returns. When this program is run on the command line, it produces the following output:

However, even if we change the test to if 2 + 3 == 6, the test passes! Try it out. It turns out that test functions always pass when their execution does not cause a crash (called a panic in Rust terminology), and it fails when it does panic. This is why testing...