Rust Bite - Rust Features

what Rust omits, changes, requires, and supports

Even if you're on the right track, you'll get run over if you just sit there.
- Will Rogers

1.0 What is Rust?

Rust resembles C++ and matches its performance potential, while adding unique and clever ideas that let it guarantee, by construction, freedom from memory handling defects and data race conditions. Rust compiles to native code and works with data safely without a garbage collector. An instance of a type like Vec<T> releases its acquired resources when it goes out of scope. The smart pointer type Box<T> manages all heap memory and releases its heap resource when it goes out of scope.
 

2.0 Performance

Rust code delivers run-time performance comparable to C++. The CommComp project compares two implementations of a message-passing channel using thread-safe blocking queues, one written in C++ and the other in Rust. It measures throughput in MBytes per Sec across several platforms, and shows that the C++ and Rust implementations deliver essentially the same throughput.
 

3.0 Rust's Look and Feel

Once you get used to the language, programming in Rust feels like using a simpler C++ with a few nice features from C# sprinkled in. An Oracle sits at your elbow with firm opinions about safe code. The Oracle fails builds when code violates its invariants: no uninitialized or null references, no sharing of mutability through references, and referend lifetimes must match or exceed the reference lifetime. The Oracle compensates for its enforcements with clear error messages that identify the offending lines of code and often suggest how to fix the problem it detected.
Thinking about Rust's Safety rules These invariants are strong conditions that imply program code cannot change data that is the target of a reference. That simplifies reasoning about program behavior, but it also seems to prevent some things we may want to build from compiling. Consider a directed graph. If we link nodes together with references, most graphs violate these safety rules. We can still build graph classes in Rust. We just cannot represent edges with references. Instead, we move nodes into a vector and establish node linkage with vector indexes. The safety rules do not cover indexes, because indexes remain valid when the vector reallocates its storage to hold more nodes. After a year of intensive coding with Rust, building more than 20 repositories of code, I built everything without unusual contortions or unsafe code blocks. I also spent much less time debugging than I have with other languages, because the compiler's clear error messages guided me toward sound implementations and I did not need to chase memory handling defects and data races.
Working with Rust's safety Oracle, called the "borrow-checker" (Rust docs refer to references as borrows), may feel disconcerting at first. Soon, however, you will treat the borrow-checker as a stern friend that often proves helpful. For a great reference on borrows, see intorust.
 

3.1 Code Sample

The dropdown below contains two examples of Rust code that emphasize creating and calling functions and methods. A quick scan gives you a taste of how Rust code operates.
Function Examples Figure 1. shows Rust code that implements a factorial function in a slightly unusual way. Inside factorial(i:u64) -> u64, an iterator (2..=i) covers the range of integers from 2 up to and including the value of i. Iteration begins when the function product() runs. The iterator trait defines many functions that make computations like this syntactically simple. The first function, demo_iter(i:64), illustrates how iterators work. We usually do not call the iterator function next() directly, but let other iterator functions, like product(), do that. They call next() and also handle the Option that indicates whether more items remain. You may have questions about some things you see here, but notice that the code looks familiar and uses clear, efficient syntax. References for Iterators and Options appear below, along with a link to the Rust Playground with this code installed. You can run it, modify the code, and see what happens.
Figure 1. Source for Factorial Demo /*-- demonstrate simple iterator --*/ fn demo_iter(i: u64) { /* iterator over 0 to i */ let mut iter = 0..=i; /* iter.next() returns Option<Some(j), None> */ loop { let opt = iter.next(); if opt.is_some() { print!( "\n iter item = {}", opt.unwrap() ); /* unwrap returns value of Some else panics */ } else { } } } /*-- -------------------------------- compute factorial with iterator Wikipedia: Rust Programming */ fn factorial(i: u64) -> u64 { (2..=i).product() } fn main() { demo_iter(5); println!(); for i in 0..=5 { print!( "\n factorial of {} = {}", i, factorial(i) ); } } Output iter item = 0 iter item = 1 iter item = 2 iter item = 3 iter item = 4 iter item = 5 factorial of 0 = 1 factorial of 1 = 1 factorial of 2 = 2 factorial of 3 = 6 factorial of 4 = 24 factorial of 5 = 120 References Rust Playground provides a web-based environment for testing small code ideas and examining assembly or WAsm representations.
Change this demo code to see what happens.
 

Code Sample - user-defined types:

Figure 2. shows a small bit of code that implements a user defined type in Rust. You may have questions about some of it, but notice again that the code looks familiar and uses clear, efficient syntax.
Figure 1. Source for User-Defined Type // CreateObject::main.rs /*----------------------------------------------- - Declare DemoObj struct, like C++ class - Request compiler impl traits Debug & Clone */ #[derive(Debug, Clone)] pub struct DemoObj { name : String } /*-- implement functions new and name --*/ impl DemoObj { pub fn new(obj_name: &str) -> DemoObj { DemoObj { name: obj_name.to_string() } } pub fn name(&self) -> &str { &self.name } } /*-- Demo DemoObj instance in action --*/ fn main() { print!( "\n -- demonstrate object creation --\n" ); let dob = DemoObj::new("Frank"); print!( "\n DemoObj instance name is {:?}", dob.name() ); let cdob = dob.clone(); print!( "\n name of clone is {:?}", cdob.name() ); print!("\n\n That's all Folks!\n\n"); } Output cargo run -q -- demonstrate object creation -- DemoObj instance name is "Frank" name of clone is "Frank" That's all Folks!   References
Our main purpose here is to present Rust fundamentals in a quick, easy to grasp way. Table 1. begins that presentation.
 

4.0 So What is Rust?

Table 1., below, lists things that distinguish the Rust programming language from C++ and C#. Rust delivers performance and memory management like C++ but adds memory and data race safety by construction. It provides memory safe operation like C#, but without the performance penalties and non-deterministic release of resources that garbage collection imposes. The table gives a quick overview of what makes Rust the language it is, describing features briefly and providing a few small code examples. References supply additional details.

Table 1. What Rust Omits, Changes, Requires, and Supports

Rust Omits: References:
Garbage Collection.
Rust uses C++ style scope-based resource management. Its clever design prevents unsound memory accesses and data races. Compile-time reference analysis, augmented with occasional run-time checks, achieves that. Rust does not allow raw pointers. References, pointers wrapped in a strict ownership policy, provide indirection.
Safety model
Ownership model
function overloading.
Not required, since constructors do not share the type name. Rust generics and traits let you define functions that operate over a set of types.
internals.rust-lang.org
StackOverflow
inheritance of non-static implementation
Rust supports inheriting a trait, which may have function definitions but cannot have data members. A struct inherits a trait through an impl statement:
impl SomeTrait for MyStruct { ... }
Traits - The Book
playground example
implicit conversion between types. All expressions must have exact type matches.
Rust supports casting with the "as" keyword and provides conversion functions for some standard types. Application programs may also provide conversion methods.
Casting - Rust by example
dereferencing raw pointers outside unsafe blocks.
Our goal: avoid unsafe blocks, and instead defer to std::library facilities where the Rust designers used, and carefully vetted, unsafe blocks to provide the functionality we need.
Unsafe - The Book
Unsafe - how and when
Rust Changes: References:
Copy Types - Only types with contiguous memory are implicitly copied.
That is the set of primitive types and aggregates that have only copy type members.
Move Types - All else are implicitly moved.
Construction, assignment, passing arguments, and returning results from functions by value move resources from source to destination. That is fast, usually just a pointer copy.
Move invalidates the source of the "moved" operation. Using a moved variable is a compile error. This is one of two frequent Gotchas for new-comers to Rust.
RustBites copy & move
playground example
semantics for copy types and move types are fixed.
Unlike C++, you do not need to, and cannot, define implicitly called copy and move constructors and assignment operators.
Rust's data management removes the need for user defined semantics.
RustBites_Data
Rust supports deep clones and defines a Clone trait that cloneable types implement.
Clones make deep copies and are always invoked explicitly.
RustBites_Data clone
playground example
Rust enumerations have elements that may wrap instances of specified types.
enum StepState { NotStarted, Reading { refs: Vec<String> }, ... }
RustStory_Data enums
RustBites_ErrHnd
playground example
Rust enumerations are often used with a matching syntax.
match state {
  StepState::NotStarted => print!("\n getting late"),
  StepState::Reading { refs } => print!("\n reading {:?}", refs),
   ...
}
RustStory_Data enums
RustBites_ErrHnd
playground example
Rust iterators are similar to C# iterators. They have many predefined adapters.
Strings have an iterator over their characters, chars().
let third_char = my_string.chars().nth(2);
RustStory iterators
RustBites iterators
std::iter::Iterator
Rust Requires: References:
Explicit declaration of mutability:
let mut x = 42;
let rx = &mut x;
RustBites_Data
playground example
No concurrent aliasing and mutation (with references)
This is the other common GotCha for those new to Rust.
A Rust program cannot read or write memory it does not own. A nearly equivalent statement: Rust will not change the contents a reference points to unless the reference is mutable and responsible for the change.
This also makes linked data structures with references difficult to build in Rust. You can build them, but it is much easier to build them with indexes in a vector container.
We will (eventually) illustrate that with a Directed Graph type that holds its vertices in a Vec<Vertex>.
RustBites_Safety playground example
References must not outlive their referends.
The Rust compiler's "borrow-checker" analyzes reference lifetimes and refuses to compile cases where it cannot prove this invariant.
Usually it does that silently, but on occasion it needs help and asks you to provide lifetime annotations. For an example, see RustBites_Options.
Understanding lifetimes
RustBites_Options
Only one owner of data
Owned resources are released when owner goes out of scope, and transferred when owner is moved.
Ownership by example
Direct access to heap storage uses the smart pointer Box<T>.
Box<T> places t ε T in the heap and implicitly dereferences the Box pointer, giving code access to T's interface. Most Rust std::library containers place their contents in the heap, e.g., vector, dequeue, map, ...
RustBites_SmrtPtrs
playground example
Function invocations on a generic type, T, require a type constrait on T using a trait declaring that function.
fn demo<T>(rt: &T) where T:Clone { let tc = rt.clone(); // use tc }
Here, clone() function is invoked on generic type rt with Clone constraint.
Traits - The Rust Book playground example
Rust Supports: References:
Rust supports error handling with enums Result<T, E> and Option<T>:
enum Result<T, E> { Ok(T), Err(E) }
enum Option<T> { Some(T), None }
RustBites Error Handling
RustStory Error Handling
RustBites Options
Rust Strings are collections of utf-8 characters, which may have sizes from 1 to 4 bytes. That lets Strings contain texts using diacritics, arabic scripts, Sanskrit, Hanzi, kangi, ...
It also means Strings cannot be indexed. Program code uses the iterator chars() instead, which detects byte sequences that mark character boundaries.
RustBites_Strings
RustBites_DataStr
RustStory_Data
std::String
std::str
Function and Type declarations and definitions may be ordered without concern for dependencies within a single file.
Functions - The Rust Book
Panic on integer underflow or overflow in debug mode. Rust the Book
Rust std::ffi library provides OsString which wraps platform specific strings and OsStr, a literal string with platform enccoding. std::ffi::OsString
std::ffi::OsStr
Rust provides PathBuf and Path which wrap OsString and OsStr, respectively, adding methods for handling paths . std::path::PathBuf, std::path::Path
Rust can generate WebAssembly code and Rust Playground can show both Rust code and WASM it generates.
Rust and WebAssembly

First Steps:

References in Table 2.a provide a great way to get started. You can work through all of them in a morning and come away with a clear idea of what Rust is all about. Pay special attention to the "Considering Rust" video.

Table 2.a - Getting your arms around Rust

Topic Description link
Why Rust? Quick survey of the main Rust concepts. Why Rust?
Rust Intro Basic introduction in three articles: Basics, Enums and Matching, and Generics. A bit long in places, but with interesting example codes. Rust in a NutShell
Ownership Very clear discussion of ownership in five short videos. intorust
Rust Survey Smart discussion that introduces the most important parts of Rust Considering Rust video
From this site, you may find explanations and references in Table 2.b useful. They summarize the beginning core of Rust. The entries carry more detail than those in Table 2.a but remain fairly quick to digest.

Table 2.b - First things to view from this site

Bite Selected Rust Bites from this site Link
Starting This page RustBites_Starting
Tooling Installing Rust, Installing Visual Studio Code, setting up, basic work flow RustBites_Tooling
Safety Rust's safety model Rustbites_Safety
Facts Quick summaries of basic Rust language information Rustbites_Facts
Flash Cards Small discussions of important Rust collections, traits, and types RustBites_FlashCards
Data Structures References for primitive and common std library types RustBites_DataStr
If you are fairly new to software development, stop here and look over the first three BuildOn Steps to get familiar with our project. Then follow the instructions in Tooling to set up Rust and Visual Studio Code. After a break, try some of the "Rust in a Nutshell" examples: copy the screen code into the VS Code editor, then compile with cargo in the attached terminal window.
The references in Table 3. offer a great place to get a quick taste of Rust and find out what it is all about. Most take about an hour of your time each.
Table 3. - References for Starting Rust
Start these references after you look at the contents of Table 1a.

Table 3. - Starting Rust at the trailhead

Topics Descriptions
Ownership by Example Nicely organized and relatively complete discussion of ownership with simple clear examples.
Introducing Structs, traits, and zero-cost abstractions A YouTube video that builds user-defined types and abstracts out key traits using simple examples. The examples get at the core of what zero-cost abstraction means.
Rust playground Playground compiles and executes Rust code from a web interface. It provides a great way to try out Rust syntax and operations.
A half-hour to learn Rust An unusual tour of Rust using small code fragments and quirky commentary.
RustTourAbbrev.pdf
RustTour.pdf
A presentation summarizing essential features of Rust. Several videos cover specific parts of the tour.
RustErrorHandling.pdf A presentation covering interesting mechanisms that Rust provides for handling program run-time errors.
In the beginning, expect to spend a lot of time getting your code to compile. After a few hours and some reading of introductory material, that improves. The good news: compiler error messages are almost always quite helpful. As you gain experience - in a week or two - you will still spend more time getting things to compile than you would with C++, but you spend much less time debugging. You will not be chasing memory errors and data races. Write code a few lines at a time, then build and run, repeating until done. That makes it much easier to locate problems and reduce compilation issues.
Cut Here: References below this line can wait for a week or two or three.
Table 2. summarized the major features of Rust and provided links to references and sample code. That "show and tell" aims to help you acquire an accurate mindset for the Rust language. Contents of the table below help you acquire much deeper knowledge of Rust through reference material and e-books. These make good companions on the Rust road. The Reference link holds many more specialized references, but these are the place to start.

Table 4. - Deeper into Rust

Topic Description link
Survey and Reference Github site with a well written collection of reference materials in a clear simple style, packed with detail. A collection of tutorial videos accompanies it. Highly recommended once you get up to speed (maybe even before then). easy rust
Code Examples Large collection of examples across the Rust language by the Rust team. Rust by Example
e-Books An e-Book surveying the best e-Books for Rust. Lots here I did not know about until I saw this. Little Book of Rust Books
Rust Cheat Sheet Very comprehensive well-organized collection of code snippets with comments. Cheats.rs
Rust Bite by Byte Sequence of pages on this site, each of which focuses on a single Rust topic RustBites
Mother of RustBites Narrative discussion of Rust in six chapters Rust Story
std Rust Libs Excellent documentation for the Rust std libraries. Very readable with access to source code. std lib
More references The place to look for specialized topics and blogs Rust Story References