about
03/12/2023
RustBites - Starting
Rust Bites Code
RustBites - Getting Started
Deeper look at "Why Rust?" Make sure you look at Table 1
Even if you're on the right track, you'll get run over if you just sit there.
- Will Rogers
- Will Rogers
1.0 What is Rust?
You will probably want to view "picture-in-picture" or "full-screen"
so details are large enough to be seen easily.
2.0 Performance
3.0 Rust's Look and Feel
Thinking about Rust's Safety rules
3.1 Code Sample
Function Examples
Code Sample - user-defined types:
4.0 So What is Rust?
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. That's achieved with compile-time reference analysis augmented with
occasional run-time checks. Raw pointers are not allowed. Indirection is achieved with references
that are pointers wrapped in a strict ownership policy.
|
Safety model Ownership model |
function overloading.
Not required since constructors do not share the type name. Rust generics and traits allow you to
define functions that will 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 can not have data members.
A struct inherits a trait by an impl statement:
|
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: use no unsafe blocks, deferring instead to std::library facilities where
the Rust designers used, and carefully vetted, unsafe blocks to provide 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.
Operations of construction, assignment, passing arguments and returning results from functions
by value will move resources from source to destination. That's 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 don't have to, and can't, define implicitly called copy and move constructors
and assignment operators.
User defined semantics are not needed due to the way data is managed in Rust.
|
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.
|
RustStory_Data enums RustBites_ErrHnd playground example |
Rust enumerations are often used with a matching syntax.
|
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().
|
RustStory iterators RustBites iterators std::iter::Iterator |
Rust Requires: | References: |
Explicit declaration of mutability:
|
RustBites_Data playground example |
No concurrent aliasing and mutation (with references)
This is the other common GotCha for those new to Rust.
This means, essentially, that a Rust program cannot read or write to memory it does not own.
One nearly equivalent statement is that Rust will not change the contents a reference points to
unless the reference is mutable and responsible for the change.
It also means that it is difficult to build linked data structures using references in Rust.
You can build them in Rust, but it is much easier to build them using indexes
in a vector container.
We will (eventually) illustrate that with a
|
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 can do that silently, but, on occasion it needs help and askes you to provide
lifetime annotations. To see an example, look at 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>.
Using Box<T> places t ε T in the heap and implicitly dereferences the Box pointer, giving
code access to T's interface. Most of the 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>:
|
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 enables Strings to contain texts using diacritics, arabic scripts, Sanskrit, Hanzi, kangi, ...
It also means that Strings cannot be indexed. Program code uses, instead, the iterator chars()
that knows how to detect byte sequences denoting 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:
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 |
Table 2.b - First things to view from this site
Bite | Selected Rust Bites from this site | Link |
---|---|---|
Starting | This page | RustBites_GettingStarting |
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 |
Table 3. - References for Starting Rust
Start these references after you've looked 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 uses simple examples for building user-defined types and abstracting out key traits. The video uses some very clever examples to get at the core of what zero-cost abstraction means. |
Rust playground | Playground is a tool for compiling and executing Rust code from a web interface. It's a great way to try out Rust syntax and operations. |
A brief introduction to Rust | Very code-centric survey of Rust with a few diagrams. This is where you start to get serious about code. Combining this tutorial with the Rust Playground (see above) will give you a big boost. |
A half-hour to learn Rust | An unusual tour of Rust using small code fragments and quirky commentary. |
RustTourAbbrev.pdf RustTour.pdf Rust Videos |
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. |
Table 4. - Deeper into Rust
Topic | Description | link |
---|---|---|
Survey and Reference | Github site with well written collection of reference materials using a clear simple style with lots of details. Also accompanied with a collection of tutorial videos. Highly recommended once you are getting 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 didn't 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 |
Table 5. - Other Intermediate References
Table 5. - Getting up to Speed
Topics | Descriptions |
---|---|
Idioms and Patterns |
|
BuildOn | BuildOn supports learning Rust by specifying Rust programs for you to complete that require several packages and use much of the Rust technology, but are otherwise relatively simple. BuildOn pages provide specification for each package and additional notes and references. |