Learning Rust
History of Rust
Rust was initially designed and developed by former Mozilla employee Graydon Hoare as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0 was released on May 15, 2015.
Initial Goals
The goal of Rust is to be a good programming language for creating highly concurrent, safe and performant systems.
"Rust is a systems programming language focused on three goals: safety, speed, and concurrency." __ Rust Documentation
Rust is very young and very modern language. It is a compiled programming language and it uses LLVM on the backend. Also, Rust is a multi-paradigm programming language, which supports imperative procedural, concurrent actor, object-oriented and pure functional styles. It also supports generic programming and metaprogramming, in both static and dynamic styles.
🔎 One of Rust’s most unique and compelling features is Ownership, which is used to achieve memory safety. Rust creates memory pointers optimistically, checks memory pointers’ limited accesses at compile-time with the usage of References and Borrowing. And it does automatic compile-time memory management by checking the Lifetimes.
Influences
Its design elements came from a wide range of sources.
- Abstract Machine Model: C
- Data types: C, SML, OCaml, Lisp, Limbo
- Optional Bindings: Swift
- Hygienic Macros: Scheme
- Functional Programming: Haskell, OCaml, F#
- Attributes: ECMA-335
- Memory Model and Memory Management: C++, ML Kit, Cyclone
- Type Classes: Haskell
- Crate: Assembly in the ECMA-335 CLI model
- Channels and Concurrency: Newsqueak, Alef, Limbo
- Message passing and Thread failure: Erlang
and etc.
Rust doesn't use an automated garbage collection system(GC) by default.
Rust compiler observes the code at compile-time and helps to prevent many types of errors that are possible to write in C, C++ like programming languages.
Before going to the next...
- The following guilds will be helpful for you to understand the maturity of the Rust ecosystem and the tools you need to choose, according to the area you want to master.
Getting Started
1. Install Rust
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
2.Try rust without installation
3. Is Rust up to date?
rustup update
4. Cargo: the Rust build tool and package manager
- build your project with
[ cargo build ] - run your project with
[ cargo run ] - test your project with
[ cargo test ] - build documentation for your project with
[ cargo doc ] - publish a library to crates.io with
[ cargo publish ] - To test that you have Rust and Cargo installed, you can run this in your terminal of choice:
[ cargo --version ]
Hello World!
1. Make a Project Directory
$ mkdir hello_world && cd $_
2. edit a main.rs as
fn main() { println!("Hello, world!"); }
3. use rustc
$ rustc main.rs
$ ls -l
total 3752
-rwxrwxr-x 1 alexlai alexlai 3834192 Jun 19 14:08 main
-rw-rw-r-- 1 alexlai alexlai 45 Jun 19 14:06 main.rs
$ ./main
Hello, world!
Anatomy of Rust Program
Let's look at the following codes that prints out "Hello, world!",
fn main() { println!("Hello, world!"); }
The main function is special: it is always the first code that runs in every executable Rust program. Here, the first line declares a function named main that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses ().
Hello Cargo
Cargo is Rust’s build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries. (We call the libraries that your code needs dependencies.)
1. Creating a Project with Cargo new
$ cargo new hello_cargo
Creating binary (application) `hello_cargo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
$ cd hello_cargo
$ tree
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
$ ls -al
total 4
drwxrwxr-x 3 alexlai alexlai 35 Jun 19 15:10 .
drwxr-xr-x 4 alexlai alexlai 133 Jun 19 15:10 ..
-rw-rw-r-- 1 alexlai alexlai 82 Jun 19 15:10 Cargo.toml
drwxrwxr-x 2 alexlai alexlai 21 Jun 19 15:10 src
Generally it will initialize a new Git repository along with a .gitignore file, unless it was under an existing git directory. You can override this behavior by using
cargo new --vcs=git project_name.
2. Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
- This file is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format.
- The first line, [package], is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections.
- The next three lines set the configuration information Cargo needs to compile your program: the name, the version, and the edition of Rust to use. We’ll talk about the edition key in Appendix E.
- The last line, [dependencies], is the start of a section for you to list any of your project’s dependencies. In Rust, packages of code are referred to as crates. We won’t need any other crates for this project, but we will in the first project in Chapter 2, so we’ll use this dependencies section then.
~/src/main.rs was auto generated by cargo new
fn main() {
println!("Hello, world!");
}
Cargo has generated a “Hello, world!” program for you and placed the code in the src directory.
Building and Running a Cargo Project
From your hello_cargo directory, build your project by entering the following command:
$ cargo build
Compiling hello_cargo v0.1.0 (/home/alexlai/mdbook-proj/learn-rust-dumindu-madunuwan/src/installation/hello_cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.94s
$ tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
├── CACHEDIR.TAG
└── debug
├── build
├── deps
│ ├── hello_cargo-1d1434a127132538
│ └── hello_cargo-1d1434a127132538.d
├── examples
├── hello_cargo
├── hello_cargo.d
└── incremental
└── hello_cargo-3iy1psz01zhx2
├── s-gx99law0wn-1mpu47x-8xdrmhemgoej4eynpe4akzbft
│ ├── 11mbs6cb0dvdfdpw.o
│ ├── 1lh00380n6tnl874.o
│ ├── 1sgpzgbsddx0q1vc.o
│ ├── 426hpberye9u6ytg.o
│ ├── 4j9q5ckxtw0qsej1.o
│ ├── dep-graph.bin
│ ├── query-cache.bin
│ ├── s50pw9t7epnr7l1.o
│ └── work-products.bin
└── s-gx99law0wn-1mpu47x.lock
9 directories, 18 files
- run it
$ ./target/debug/hello_cargo
Hello, world!
- use
cargo run
$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
Running `target/debug/hello_cargo`
Hello, world!
- or,
cargo check
$ cargo check
Checking hello_cargo v0.1.0 (/home/alexlai/mdbook-proj/learn-rust-dumindu-madunuwan/src/installation/hello_cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12s
Summary
- We can create a project using
cargo new. - We can build a project using
cargo build. - We can build and run a project in one step using
cargo run. - We can build a project without producing a binary to check for errors using
cargo check. - Instead of saving the result of the build in the same directory as our code, Cargo stores it in the
target/debugdirectory.
Building for Release
When your project is finally ready for release, you can use cargo build --release to compile it with optimizations. This command will create an executable in target/release instead of target/debug.
For more information about Cargo, check out The Cargo Book.
Programming a Guessing Game
Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit.
Setting Up a New Project
$ cargo new guessing_game_proj && cd guessing_game_proj
Creating binary (application) `guessing_game_proj` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
$ tree
.
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
- Look at the generated Cargo.toml file:
[package]
name = "guessing_game_proj"
version = "0.1.0"
edition = "2021"
[dependencies]
- and the src/main.rs as,
fn main() { println!("Hello, world!"); }
- compile and run
$ cargo run
Compiling guessing_game_proj v0.1.0 (/home/alexlai/mdbook-proj/learn-rust-dumindu-madunuwan/src/gussing_game/guessing_game_proj)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.98s
Running `target/debug/guessing_game_proj`
Hello, world!
Processing a Guess
The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess.
- Enter the code in src/main.rs,
use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {}", guess); }}
Rust Libraries
Rust libraries are collections of pre-written code that developers can use to perform common tasks or extend the functionality of their Rust programs. These libraries provide reusable components, which help save time and effort by allowing developers to leverage existing solutions rather than writing code from scratch. Rust libraries can cover a wide range of functionalities, including data structures, algorithms, networking, file I/O, cryptography, and more.
Here are some key points about Rust libraries:
- Crates and Cargo:
- In Rust, libraries are often packaged as "crates." A crate can be a library or an executable program. Rust’s package manager, Cargo, is used to manage these crates. It handles dependencies, compilation, and distribution of Rust code.
- Crates.io:
- This is the central repository for Rust libraries. Developers can publish their crates to Crates.io, making them available for others to use. It’s similar to npm for JavaScript or PyPI for Python.
Common Rust Libraries:
- serde: A framework for serializing and deserializing Rust data structures.
- tokio: An asynchronous runtime for the Rust programming language.
- hyper: A fast and correct HTTP implementation.
- rand: A library for random number generation.
- regex: A library for regular expressions.
Creating and Using Libraries:
- Creating:
- Developers can create a library by setting up a new Cargo project with
cargo new --lib library_name. They can then define their functions, structs, and other items within this library.
- Developers can create a library by setting up a new Cargo project with
- Using:
- To use a library, developers specify the library as a dependency in the Cargo.toml file of their project. Cargo then handles downloading and integrating the library.
- Documentation and Examples:
- Rust libraries often come with extensive documentation and examples. Rust’s emphasis on documentation ensures that libraries are usually well-documented, making it easier for developers to understand and use them.
- Open Source:
- Many Rust libraries are open source, allowing developers to contribute to their development, report issues, or fork them to create their own versions.
Example
Here is an example of how you might use the serde library for serialization in a Rust project:
- Add serde to your Cargo.toml:
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
- Use serde in your Rust code:
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize)] struct Person { name: String, age: u8, } fn main() { let person = Person { name: String::from("Alice"), age: 30, }; // Serialize to a JSON string. let serialized = serde_json::to_string(&person).unwrap(); println!("Serialized: {}", serialized); // Deserialize back to a Rust struct. let deserialized: Person = serde_json::from_str(&serialized).unwrap(); println!("Deserialized: {} is {} years old", deserialized.name, deserialized.age); }
This example demonstrates how to serialize and deserialize a Rust struct using the serde and serde_json libraries.
Basics
Common Programming Concepts
This section covers concepts that appear in almost every programming language and how they work in Rust. Many programming languages have much in common at their core. None of the concepts presented in this chapter are unique to Rust, but we’ll discuss them in the context of Rust and explain the conventions around using these concepts.
Specifically, you’ll learn about variables, basic types, functions, comments, primitive data, and control flow. These foundations will be in every Rust program, and learning them early will give you a strong core to start from.
Keywords The Rust language has a set of keywords that are reserved for use by the language only, much as in other languages. Keep in mind that you cannot use these words as names of variables or functions. Most of the keywords have special meanings, and you’ll be using them to do various tasks in your Rust programs; a few have no current functionality associated with them but have been reserved for functionality that might be added to Rust in the future. You can find a list of the keywords in Appendix A.
Primitive Data Types
Primitive Data Types means that they’re built-in to the language. Rust is structured in such a way that the standard library also provides a number of useful types built on top of these ones, as well, but these are the most primitive.
true or false
#![allow(unused)] fn main() { let x = true; let y: bool = false; // ⭐️ no TRUE, FALSE, 1, 0 }
A single Unicode scalar value
#![allow(unused)] fn main() { let x = 'x'; let y: char = '😎'; // ⭐️ no "x", only single quotes }
Because of Unicode support, char is not a single byte, but four(32 bits).
8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types
| DATA TYPE | MIN | MAX |
|---|---|---|
| i8 | -128 | 127 |
| i16 | -32768 | 32767 |
| i32 | -2147483648 | 2147483647 |
| i64 | -9223372036854775808 | 9223372036854775807 |
| i128 | -170141183460469231731687303715884105728 | 170141183460469231731687303715884105727 |
💡 The min and max values are based on the following equation; from -(2ⁿ⁻¹) to 2ⁿ⁻¹-1. You can use min_value() and max_value() functions to find min and max of each integer type. ex.i8::min_value();
#![allow(unused)] fn main() { let x = 10; // ⭐️ The default integer type in Rust is i32 let y: i8 = -128; }
8, 16, 32, 64 and 128 bit fixed sized unsigned(0/+) integer types
| DATA TYPE | MIN | MAX |
|---|---|---|
| u8 | 0 | 255 |
| u16 | 0 | 65535 |
| u32 | 0 | 4294967295 |
| u64 | 0 | 18446744073709551615 |
| u128 | 0 | 340282366920938463463374607431768211455 |
💡 The min and max values are based on the following equation; from 0 to 2ⁿ-1. Same way you can use min_value() and max_value() functions to find min and max of each integer type. ex.u8::max_value();
Pointer sized signed and unsigned integer types
The actual bit size depends on the computer architecture you are compiling your program for. By default, the sizes are equal to 32 bits on 32-bit platforms and 64 bits on 64-bit platforms.
🔎 Search more about cross-compiling and supported tiers of Rust programs.
32 and 64 bit sized floating point numbers(numbers with decimal points)
Rust follows IEEE Standard for Binary Floating-Point Arithmetic. The f32 type is similar to float(Single precision) in other languages, while f64 is similar to double(Double precision) in other languages.
#![allow(unused)] fn main() { let x = 1.5; // ⭐️ The default float type in Rust is f64 let y: f64 = 2.0; }
💡 Should avoid using f32, unless you need to reduce memory consumption badly or if you are doing low-level optimization, when targeted hardware does not support for double-precision or when single-precision is faster than double-precision on it.
Fixed size list of elements of same data type
#![allow(unused)] fn main() { let a = [1, 2, 3]; let a: [i32; 3] = [1, 2, 3]; // [Type; NO of elements] let b: [i32; 0] = []; // An empty array let mut c: [i32; 3] = [1, 2, 3]; c[0] = 2; c[1] = 4; c[2] = 6; println!("{:?}", c); // [2, 4, 6] println!("{:#?}", c); // [ // 2, // 4, // 6, // ] let d = [0; 5]; // [0, 0, 0, 0, 0] let e = ["x"; 5]; // ["x", "x", "x", "x", "x"] }
⭐️ Arrays are immutable by default and even with mut, its element count cannot be changed.
🔎 If you are looking for a dynamic/ growable array, you can use vectors. Vectors can contain any type of elements but all elements must be in the same data type.
Fixed size ordered list of elements of different(or same) data types
#![allow(unused)] fn main() { let a = (1, 1.5, true, 'a'); let a: (i32, f64, bool, char) = (1, 1.5, true, 'a'); let mut b = (1, 1.5); b.0 = 2; b.1 = 3.0; println!("{:?}", b); // (2, 3.0) println!("{:#?}", b); // ( // 2, // 3.0, // ) let (c, d) = b; // c = 2, d = 3.0 let (e, _, _, f) = a; // e = 1, f = 'a' let g = (0,); // single-element tuple let h = (b, (2, 4), 5); // ((2, 3.0), (2, 4), 5) }
⭐️ Tuples are also immutable by default and even with mut, its element count cannot be changed. Also, if you want to change an element’s value, the new value should have the same data type of previous value.
Dynamically-sized reference to another data structure
Imagine you want to get/ pass a part of an array or any other data structure. Instead of copying it to another array (or same data structure), Rust allows for creating a view/ reference to access only that part of the data. This view/ reference can be mutable or immutable.
#![allow(unused)] fn main() { let a: [i32; 4] = [1, 2, 3, 4]; // Parent Array let b: &[i32] = &a; // Slicing whole array let c = &a[0..4]; // From 0th position to 4th(excluding) let d = &a[..]; // Slicing whole array let e = &a[1..3]; // [2, 3] let f = &a[1..]; // [2, 3, 4] let g = &a[..3]; // [1, 2, 3] }
Unsized UTF-8 sequence of Unicode string slices
#![allow(unused)] fn main() { let a = "Hello, world."; // a: &'static str let b: &str = "こんにちは, 世界!"; }
⭐️ It's an immutable/ statically allocated slice holding an unknown sized sequence of UTF-8 code points stored in somewhere in memory. &str is used to borrow and assign the whole array to the given variable binding.
As we discussed in the functions section as well, p1 is a function pointer to plus_one() in the following code.
fn main() { let p1: fn(i32) -> i32 = plus_one; let x = p1(5); // 6 } fn plus_one(a: i32) -> i32 { a + 1 }
Before going to the next...
- In Rust, the default integer type is
i32and the default float type isf64.
#![allow(unused)] fn main() { let i = 10; // Equals to `let i: i32 = 10;` let f = 3.14; // Equals to `let f: f64 = 3.14;` }
- Other than adding the type annotations to the variables, for numeric types, we can append the data type directly to the value as the suffix. Also, to improve the readability of long numbers, we can use
_as a divider.
#![allow(unused)] fn main() { let a = 5i8; // Equals to `let a: i8 = 5;` let b = 100_000_000; // Equals to `let b = 100000000;` // 💡 The placements of _s are not strict. ex. 10000_0000 is also valid. let pi = 3.141_592_653_59f64; // Equals to `let pi: f64 = 3.14159265359` const PI: f64 = 3.141_592_653_59; // In the constants and statics, the data type must be annotated in the beginning. }
-
There are several string types in Rust. The
Stringtype is a heap-allocated string. This string is growable and is also guaranteed to be UTF-8. In general, you should useStringwhen you needownership, and&strwhen you just need to borrow a string. -
A
Stringtype can be generated from a&strtype, via theto_string()orString::from()methods. Withas_str()method, aStringtype can be converted to a&strtype.
#![allow(unused)] fn main() { let s: &str = "Hello"; // &str let s = s.to_string(); // String let s = String::from(s); // String let s = s.as_str(); // &str }
String slices
What Is a String?
Primitive Type Array
A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N.
Primitive Type array, std docs
There are two syntactic forms for creating an array:
- A list with each element, i.e., [x, y, z].
- A repeat expression [x; N], which produces an array with N copies of x. The type of x must be Copy.
- [expr; 0] is allowed, and produces an empty array. This will still evaluate expr, however, and immediately drop the resulting value, so be mindful of side effects.
Examples,
#![allow(unused)] fn main() { let mut array: [i32; 3] = [0; 3]; array[1] = 1; array[2] = 2; println!("{:?}", array); // -> [0, 1, 2] println!("{:?}", &array); //-> [0, 1, 2] // get a slice from array[n..m] // from nth position to mth position(excluding) println!("{:?}", &array[1..]); //-> [1, 2] println!("{:?}", &array[..]); // -> [0, 1, 2] println!("array.len(): {}", array.len()); // -> array.len(): 3 println!("{:?}", &array[..array.len() - 1]); // => [0, 1] println!("{:?}", &array[..array.len()]); // -> [0, 1, 2] println!("{:?}", &array[array.len()..array.len()]); // -> [] assert_eq!([1, 2], &array[1..]); // This loop prints: 0 1 2 // for x in array { } // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied for x in &array { print!("{} ", x); //-> 0 1 2 } println!("using array.iter()"); for x in array.iter() { print!("{} ", x); //-> 0 1 2 } }
You can use a slice pattern to move elements out of an array:
// The following example is not working, to be continued!!!
fn main() { fn move_away(a: str) -> str { /* Do interesting things. */ a.to_uppercase() } let [mut john, roa] = ["John".to_string(), "Roa".to_string()]; john = move_away(&john); // move_away(roa); println!("{:?}", john); println!("{:?}", john); }
以下:分かりません
Arrays of any size implement the following traits if the element type allows it:
- Copy
- Clone
- Debug
- IntoIterator, implemented for &[T; N] and &mut [T; N])
- PartialEq, PartialOrd, Eq, Ord
- ]Hash](https://doc.rust-lang.org/stable/std/hash/trait.Hash.html)
- AsRef, AsMut
- Borrow, BorrowMut
Functions
Named functions
- Named functions are declared with the keyword
fn - Style for function and variable names. In snake_case.
- When using arguments, you must declare the data types.
- By default, functions return an empty tuple/
(). If you want to return a value, the return type must be specified after->
i. Hello world
fn main() { println!("Hello, world!"); }
ii. Passing arguments
#![allow(unused)] fn main() { fn print_sum(a: i8, b: i8) { println!("sum is: {}", a + b); } }
iii. Returning values
#![allow(unused)] fn main() { // 01. Without the return keyword. Only the last expression returns. fn plus_one(a: i32) -> i32 { a + 1 // There is no ending ; in the above line. // It means this is an expression which equals to `return a + 1;`. } }
#![allow(unused)] fn main() { // 02. With the return keyword. fn plus_two(a: i32) -> i32 { return a + 2; // Should use return keyword only on conditional/ early returns. // Using return keyword in the last expression is a bad practice. } }
iv. Function pointers, Usage as a Data Type
fn main() { // 01. Without type declarations. let p1 = plus_one; let x = p1(5); // 6 // 02. With type declarations. let p1: fn(i32) -> i32 = plus_one; let x = p1(5); // 6 } fn plus_one(a: i32) -> i32 { a + 1 }
Closures
- Also known as anonymous functions or lambda functions.
- The data types of arguments and returns are optional ⃰ⁱᵛ.
Example with a named function, before using closures.
fn main() { let x = 2; println!("{}", get_square_value(x)); } fn get_square_value(i: i32) -> i32 { i * i }
i. With optional type declarations of input and return types
fn main() { let x = 2; let square = |i: i32| -> i32 { // Input parameters are passed inside | | and expression body is wrapped within { } i * i }; println!("{}", square(x)); }
ii. Without type declarations of input and return types
fn main() { let x = 2; let square = |i| i * i; // { } are optional for single-lined closures println!("{}", square(x)); }
iii. With optional type declarations; Creating and calling together
fn main() { let x = 2; let x_square = |i: i32| -> i32 { i * i }(x); // { } are mandatory while creating and calling same time. println!("{}", x_square); }
iv. Without optional type declarations; Creating and calling together
fn main() { let x = 2; let x_square = |i| -> i32 { i * i }(x); // ⭐️ The return type is mandatory. println!("{}", x_square); }
Pass-By-Value or Reference?
by Ryan Levick · 2018.9.12
Let's look at this examples first,
#[allow(unused_assignments)] fn multiply(mut arg1: i32, arg2: &mut i32) -> i32 { let ret = arg1 * *arg2; arg1 = ret; *arg2 = ret; return ret; } fn main() { let arg1:i32 = 2; let mut arg2:i32 = 3; let ret = multiply(arg1, &mut arg2); // prints 2 because it's passed by value println!("arg1: {}", arg1); //-> arg1: 2 // prints 6 because it's passed by mutable reference println!("arg2: {}", arg2); //-> arg2: 6 // prints 6 println!("ret: {}", ret); // -> ret: 6 }
Standard Library Types
Standard Library, Primitives and Preludes
⭐️ In Rust, language elements are implemented by not only std library crate but also compiler as well. Examples,
- Primitives: Defined by the compiler and methods are implemented by std library directly on primitives.
- Standard Macros: Defined by both compiler and std
The std library has been divided into modules, according to the main areas each covered.
⭐️ While primitives are implemented by the compiler, the standard library implements the most useful methods directly on the primitive types. But some rarely useful language elements of some primitives are stored on relevant std modules. This is why you can see char, str and integer types on both primitives and std modules.
What is String?
Common Collections
Rust’s standard library includes a number of very useful data structures called collections. Most other data types represent one specific value, but collections can contain multiple values. Unlike the built-in array and tuple types, the data these collections point to is stored on the heap, which means the amount of data does not need to be known at compile time and can grow or shrink as the program runs. Each kind of collection has different capabilities and costs, and choosing an appropriate one for your current situation is a skill you’ll develop over time. In this chapter, we’ll discuss three collections that are used very often in Rust programs:
- A vector allows you to store a variable number of values next to each other.
- A string is a collection of characters. We’ve mentioned the String type previously, but in this chapter we’ll talk about it in depth.
- A hash map allows you to associate a value with a particular key. It’s a particular implementation of the more general data structure called a map.
To learn about the other kinds of collections provided by the standard library, see the documentation.
We’ll discuss how to create and update vectors, strings, and hash maps, as well as what makes each special.
Vectors
Here is the summary by learn-rust/Dumindu Madunuwan.
If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of a re-sizable array but all elements must be in the same type.
⭐️ It’s a generic type, written as Vec<T> . T can have any type, ex. The type of a Vec of i32s is Vec<i32>. Also, Vectors always allocate their data in a dynamically allocated heap.
Create empty vector
#![allow(unused)] fn main() { let mut a = Vec::new(); //1.With new() keyword let mut b = vec![]; //2.Using the vec! macro }
Create with data types
#![allow(unused)] fn main() { let mut a2: Vec<i32> = Vec::new(); let mut b2: Vec<i32> = vec![]; let mut b3 = vec![1i32, 2, 3];//Sufixing 1st value with data type let mut b4 = vec![1, 2, 3]; let mut b5: Vec<i32> = vec![1, 2, 3]; let mut b6 = vec![1i32, 2, 3]; let mut b7 = vec![0; 10]; //Ten zeroes }
Access and change data
#![allow(unused)] fn main() { //Accessing and changing existing data let mut c = vec![5, 4, 3, 2, 1]; c[0] = 1; c[1] = 2; //c[6] = 2; Cannot assign values this way, index out of bounds println!("{:?}", c); //[1, 2, 3, 2, 1] //push and pop let mut d: Vec<i32> = Vec::new(); d.push(1); //[1] : Add an element to the end d.push(2); //[1, 2] d.pop(); //[1] : : Remove an element from the end // 🔎 Capacity and reallocation let mut e: Vec<i32> = Vec::with_capacity(10); println!("Length: {}, Capacity : {}", e.len(), e.capacity()); //Length: 0, Capacity : 10 // These are all done without reallocating... for i in 0..10 { e.push(i); } // ...but this may make the vector reallocate e.push(11); }
⭐️ Mainly a vector represent 3 things,
- A pointer to the data
- No of elements currently have(length)
- Capacity (Amount of space allocated for any future elements).
If the length of a vector exceeds its capacity, its capacity will be increased automatically. But its elements will be reallocated(which can be slow). So always use Vec::with_capacity whenever it’s possible.
💡 The String data type is a UTF-8 encoded vector. But you can not index into a String because of encoding.
💯 Vectors can be used with iterators in three ways,
#![allow(unused)] fn main() { let mut v = vec![1, 2, 3, 4, 5]; for i in &v { println!("A reference to {}", i); } for i in &mut v { println!("A mutable reference to {}", i); } for i in v { println!("Take ownership of the vector and its element {}", i); } }
Module std::vec
Storing Lists of Values with Vectors
The first collection type we’ll look at is Vec
Creating a New Vector
To create a new, empty vector, we can call the Vec::new function,
fn main() { let v: Vec<i32> = Vec::new(); }
Beyond The Basics
In this section, we are going to conver,
- Vectors, written as Vec
. - A vector is kind of a re-sizable array but all elements must be in the same type.
- ⭐️ It’s a generic type, written as Vec
. T can have any type, ex. The type of a Vec of i32s is Vec . Also, Vectors always allocate their data in a dynamically allocated heap. - let v: Vec
= Vec::new(); will create a new empty Vector. - Vectors are implemented using generics, Vec
type provided by the standard library can hold any type, and when a specific vector holds a specific type, the type is specified within angle brackets. - using vec! macro, let v = vec![1, 2, 3];, this will create a new Vec
- Structs
- Enums
- Generics
- Impls ans Traits
Vectors
If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of a re-sizable array but all elements must be in the same type.
⭐️ It’s a generic type, written as Vec<T> . T can have any type, ex. The type of a Vec of i32s is Vec<i32>. Also, Vectors always allocate their data in a dynamically allocated heap.
⭐️ You can create them with the vec! macro.
Create empty vector
#![allow(unused)] fn main() { let mut a = Vec::new(); //1.With new() keyword let mut b = vec![]; //2.Using the vec! macro }
Create with data types
#![allow(unused)] fn main() { let mut a2: Vec<i32> = Vec::new(); let mut b2: Vec<i32> = vec![]; let mut b3 = vec![1i32, 2, 3];//Sufixing 1st value with data type let mut b4 = vec![1, 2, 3]; let mut b5: Vec<i32> = vec![1, 2, 3]; let mut b6 = vec![1i32, 2, 3]; let mut b7 = vec![0; 10]; //Ten zeroes }
Access and change data
#![allow(unused)] fn main() { //Accessing and changing existing data let mut c = vec![5, 4, 3, 2, 1]; c[0] = 1; c[1] = 2; //c[6] = 2; Cannot assign values this way, index out of bounds println!("{:?}", c); //[1, 2, 3, 2, 1] //push and pop let mut d: Vec<i32> = Vec::new(); d.push(1); //[1] : Add an element to the end d.push(2); //[1, 2] d.pop(); //[1] : : Remove an element from the end println!("{:?}", d); // -> [1] // 🔎 Capacity and reallocation let mut e: Vec<i32> = Vec::with_capacity(10); println!("Length: {}, Capacity : {}", e.len(), e.capacity()); //Length: 0, Capacity : 10 // These are all done without reallocating... for i in 0..10 { e.push(i); } // ...but this may make the vector reallocate e.push(10); println!("{:?}", e); // -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] println!("Length: {}, Capacity : {}", e.len(), e.capacity()); // -> Length: 11, Capacity : 20 for i in 11..20 { e.push(i); } // ...but this may make the vector reallocate e.push(20); println!("{:?}", e); // -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] println!("Length: {}, Capacity : {}", e.len(), e.capacity()); // -> Length: 21, Capacity : 40 }
⭐️ Mainly a vector represents,
- A pointer to the data
- No of elements currently have(length)
- Capacity (Amount of space allocated for any future elements).
If the length of a vector exceeds its capacity, its capacity will be increased automatically. But its elements will be reallocated(which can be slow). So always use Vec::with_capacity whenever it’s possible.
💡 The String data type is a UTF-8 encoded vector. But you can not index into a String because of encoding.
💯 Vectors can be used with iterators in three ways,
#![allow(unused)] fn main() { let mut v = vec![1, 2, 3, 4, 5]; for i in &v { println!("A reference to {}", i); } for i in &mut v { println!("A mutable reference to {}", i); } for i in v { println!("Take ownership of the vector and its element {}", i); } }
Strings
Strings are an important concept for any programmer to master. Rust’s string handling system is a bit different from other languages, due to its systems focus. Any time you have a data structure of variable size, things can get tricky, and strings are a re-sizable data structure. That being said, Rust’s strings also work differently than in some other systems languages, such as C.
Let’s dig into the details. A ‘string’ is a sequence of Unicode scalar values encoded as a stream of UTF-8 bytes. All strings are guaranteed to be a valid encoding of UTF-8 sequences. Additionally, unlike some systems languages, strings are not NUL-terminated and can contain NUL bytes.
Rust has two main types of strings: &str and String. Let’s talk about &str first. These are called ‘string slices’. A string slice has a fixed size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes.
let greeting = "Hello there."; // greeting: &'static str
The Tough Part
Rust language is too hard to learn and use, says user survey
A survey of Rust users finds difficulty and frustration with the language’s highly touted features for memory safety and correctness
Rust’s big claim to fame is a mix of speed and memory safety. Rust code compiles to machine-native instructions, and the syntax and idioms around memory management—lifetimes and borrowing—make it difficult for memory-unsafe code to compile at all. But users still have trouble understanding those metaphors.
We are going to cover:
- Ownership
- Borrowing
- LifeTimes
Types
Types
Every variable, item and value in a Rust program has a type. The type of a value defines the interpretation of the memory holding it.
Built-in types are tightly integrated into the language, in nontrivial ways that are not possible to emulate in user-defined types. User-defined types have limited capabilities.
Primitive types
- Some types are defined by the language, rather than as part of the standard library, these are called primitive types. Some of these are individual types:
- The boolean type bool with values true and false.
- The machine types (integer and floating-point).
- The machine-dependent integer types.
- The textual types char and str.
- There are also some primitive constructs for generic types built in to the language:
- Tuples
- Arrays
- Slices
- Function pointers
- References
- Pointers
Reference and Pointer Types
All pointers in Rust are explicit first-class values. They can be moved or copied, stored into data structs, and returned from functions.
Shared references (&)
These point to memory owned by some other value. When a shared reference to a value is created it prevents direct mutation of the value. Interior mutability provides an exception for this in certain circumstances. As the name suggests, any number of shared references to a value may exit. A shared reference type is written &type, or &'a type when you need to specify an explicit lifetime. Copying a reference is a "shallow" operation: it involves only copying the pointer itself, that is, pointers are Copy. Releasing a reference has no effect on the value it points to, but referencing of a temporary value will keep it alive during the scope of the reference itself.
Mutable references (&mut)
These also point to memory owned by some other value. A mutable reference type is written &mut type or &'a mut type. A mutable reference (that hasn't been borrowed) is the only way to access the value it points to, so is not Copy.
Raw pointers (*const and *mut)
Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written as *const T or *mut T, for example *const i32 means a raw pointer to a 32-bit integer. Copying or dropping a raw pointer has no effect on the lifecycle of any other value. Dereferencing a raw pointer is an unsafe operation, this can also be used to convert a raw pointer to a reference by reborrowing it (&* or &mut *). Raw pointers are generally discouraged in Rust code; they exist to support interoperability with foreign code, and writing performance-critical or low-level functions.
When comparing pointers they are compared by their address, rather than by what they point to. When comparing pointers to dynamically sized types they also have their addition data compared.
Smart Pointers
The standard library contains additional 'smart pointer' types beyond references and raw pointers.
Reference Types
References, both shared and mutable.
A reference represents a borrow of some owned value. You can get one by using the & or &mut operators on a value, or by using a ref or ref mut pattern.
For those familiar with pointers, a reference is just a pointer that is assumed to be aligned, not null, and pointing to memory containing a valid value of T - for example, &bool can only point to an allocation containing the integer values 1 (true) or 0 (false), but creating a &bool that points to an allocation containing the value 3 causes undefined behaviour. In fact, Option<&T> has the same memory representation as a nullable but aligned pointer, and can be passed across FFI boundaries as such.
In most cases, references can be used much like the original value. Field access, method calling, and indexing work the same (save for mutability rules, of course). In addition, the comparison operators transparently defer to the referent's implementation, allowing references to be compared the same as owned values.
References have a lifetime attached to them, which represents the scope for which the borrow is valid. A lifetime is said to "outlive" another one if its representative scope is as long or longer than the other. The 'static lifetime is the longest lifetime, which represents the total life of the program. For example, string literals have a 'static lifetime because the text data is embedded into the binary of the program, rather than in an allocation that needs to be dynamically managed.
&mut T references can be freely coerced into &T references with the same referent type, and references with longer lifetimes can be freely coerced into references with shorter ones.
Reference equality by address, instead of comparing the values pointed to, is accomplished via implicit reference-pointer coercion and raw pointer equality via ptr::eq, while PartialEq compares values.
Example 1,
#![allow(unused)] fn main() { use std::ptr; let five = 5; let other_five = 5; let five_ref = &five; let same_five_ref = &five; let other_five_ref = &other_five; println!("five_ref: {:?}, same_five_ref: {:?}", five_ref, same_five_ref); println!("five_ref: {:p}, same_five_ref: {:p}", five_ref, same_five_ref); assert!(five_ref == other_five_ref); assert!(ptr::eq(five_ref, same_five_ref)); println!("five_ref: {:?}, other_five_ref: {:?}", five_ref, other_five_ref); println!("five_ref: {:p}, other_five_ref: {:p}", five_ref, other_five_ref); assert!(!ptr::eq(five_ref, other_five_ref)); }
Example 2,
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len // -> The length of 'hello' is 5. } fn calculate_length(s: &String) -> usize { s.len() }
Pointer Types
Rust's pointers are one of its more unique and compelling features. Pointers are also one of the more confusing topics for newcomers to Rust. They can also be confusing for people coming from other languages that support pointers, such as C++.
An introduction
If you aren't familiar with the concept of pointers, here's a short introduction. Pointers are a very fundamental concept in systems programming languages, so it's important to understand them.
Pointer Basics
When you create a new variable binding, you're giving a name to a value that's stored at a particular location on the stack. (If you're not familiar with the heap vs. stack, please check out this Stack Overflow question, as the rest of this guide assumes you know the difference.) Like this:
fn main() { let x = 5; let y = 8; println!("x address: {:p}", &x); println!("y address: {:p}", &y); }
| variable | location | value |
|---|---|---|
| x | 0x7ffed0010e60 (varies) | 5 |
| y | 0x7ffed0010e64 (varies) | 8 |
See the difference? Rather than contain a value, the value of a pointer is a location in memory. In this case, the location of y. x and y have the type i32, but z has the type &i32. We can print this location using the {:p} format string:
fn main() { let x = 5; let y = 8; let z = &y; println!("&y address: {:p}", &y); // -> &y address: 0x7ffecbc161cc println!("z address: {:p}", z); // -> z address: 0x7ffecbc161cc }
Because i32 and &i32 are different types, we can't, for example, add them together:
fn main() { let x = 5; let y = 8; let z = &y; // unlioke this articale was written, it will cause error println!("{}", x + z); // version 1.51.0, -> 13 println!("{}", x + *z);// version 1.51.0, -> 13 println!("{}", x + &y);// version 1.51.0, -> 13 }
That's it! That's all pointers are: they point to some memory location. Not much else to them. Now that we've discussed the what of pointers, let's talk about the why.
Rust: Pass-By-Value or Pass-By-Reference?
- pass-by-value means that when passing an argument to a function it gets copied into the new function so that the value in the calling function and the value in the called function are two separate values. Changes to one will not in turn result in the same change to the other.
- Pass-by-reference, on the other hand, means that when passing an argument to a function, it doesn’t copy the value but rather the argument is merely a transparent reference to the original value. This means changes to the value in the called function change the value in the calling function since they are the same value.
Rust is strictly a pass-by-value language.
This might surprise you since references play a big part in the language. However, references in Rust are first class citizens. They, themselves, are values that can be passed - by value - to a function.
Let’s take a look at some examples:
fn main() { let n_main: usize = 100; println!("n_main address: {:p}", &n_main); // -> n_main address: 0x7ffc85a69758 let inc = inc(n_main); println!("inc addr: {:p}", &inc); // -> inc addr: 0x7ffc85a697b0 println!("inc: {}", inc); // -> 101 println!("n_name: {}", n_main); // -> n_name: 100 } fn inc(n_inc: usize) -> usize { println!("n_inc address: {:p}", &n_inc); // -> n_inc address: 0x7ffc85a69638 println!("n_inc: {:?}", n_inc); // -> n_inc: 100 n_inc + 1 }
- n_main is a number allocated on the stack of the main function.
- When we pass n_main to the inc function it is copied to the stack of the inc function.
- n_main and n_inc are two separate values at two places in memory.
fn main() { let n_main: usize = 100; let n_main_ref: &usize = &n_main; println!("&n_main: {:p}, n_main_ref: {:p}", &n_main, n_main_ref ); // &n_main: 0x7ffec91507d0, n_main_ref: 0x7ffec91507d0 let inc = inc_ref(n_main_ref); println!("inc addr: {:p}", &inc); // -> inc addr: 0x7ffec9150848 println!("inc: {}", inc); // -> inc: 101 } fn inc_ref(n_inc_ref: &usize) -> usize { println!("n_inc_ref: {:p}", n_inc_ref); // -> n_inc_ref: 0x7ffec91507d0 n_inc_ref + 1 }
- the function inc_ref works the same way as inc did before just now with the value being a reference instead of a number of type usize.
- When we pass n_main_ref to inc_ref, the reference value n_main_ref (not the value that it’s pointing to) is copied to the stack of inc_ref.
- The reference is a value and it behaves with pass-by-value semantics just like the value of type usize did.
Let’s take a look at another example to drive the case home:
⭐️ the array is a fixed-size list of elements, of the same data type. Even with mut, its element count can not be changed. While A vector is kind of a re-sizable array but all elements must be in the same type.
fn main() { let array_main: [Vec<u8>; 3] = [vec![1], vec![2, 4], vec![]]; print(array_main); } fn print(array: [Vec<u8>; 3]) { for e in array.iter() { println!("{:?}", e) } } /* * output: * [1] * [2, 4] * [] */
This example is the exact same as the above examples except the underlying value we’re looking at is a fixed length array with elements that are Vecs. In the case of the print function, the array will be copied from the stack of the main function to the stack of the print function. This means that each of the three elements (the Vecs) will be copied to the new stack frame.
It’s important to be clear what “copying” means here. While logically we might think of a Vec as a growable array on the heap, in reality is is just a struct that contains three values: a length, a capacity and a pointer to the actual data on the heap. When we say the Vec is copied - we mean this struct is copied. The data on the heap, however, is not copied.
Now if Rust didn’t have the borrow checker this could present a problem. Why? Copying one of the Vecs would lead to two pointers (a.k.a. aliased pointers) to the same data on the heap. If we then “dropped” (a.k.a freed, a.k.a. deallocated, a.k.a. destroyed) one of the Vecs (and in turn free the heap allocated memory), the pointer in other Vec would now point to junk data. Luckily, the borrow checker makes it impossible to use array_main after it’s been “moved” to the print function.
Ok, now let’s look again at passing a reference by value:
fn main() { let array_main: [Vec<u8>; 3] = [vec![1], vec![2, 4], vec![]]; let array_main_ref: &[Vec<u8>] = &array_main; print(array_main_ref); } fn print(array_ref: &[Vec<u8>]) { for e in array_ref.iter() { println!("{:?}", e) } } /* * output: * [1] * [2, 4] * [] */
This example again is pass-by-value semantics. The value in question is the reference to our stack allocated array. The reference array_main_ref will be copied from main’s stack to the stack of the print function, but of course, the array itself will not be copied and will stay on the stack of the main function.
Ownership
Understanding Ownership
Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector. Therefore, it’s important to understand how ownership works in Rust. In this chapter, we’ll talk about ownership as well as several related features: borrowing, slices, and how Rust lays data out in memory
What Is Ownership?
All programs have to manage the way they use a computer’s memory while running. Some languages have garbage collection that constantly looks for no longer used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory. Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks at compile time. None of the ownership features slow down your program while it’s running.
Ownership in a nutshell, by Héla Ben Khalfallah, Jun 1, 2020
How does Rust manage memory ?
- Stack: It’s a special region of your computer’s memory that stores temporary variables created by each function. When a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature (variable scope, or local).
- Primitive values such as numbers, characters, and true/false values are stored on the stack (stack is LIFO).
- Heap : Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.
- While the value of more complex objects or types that could grow in size are stored in the heap memory.
For examples,
let my_string = "hello";
Data with known size at compile time, i.e. my_string, is stored in stack because we know size of the string literal at compile time.
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
fn main() { { let hello = "Hello, World!"; println!("{}", hello); } // varibale hello is now invalid! println!("{}", hello); }
Ownership again
fn main() { let a = [1, 2, 3]; let b = a; println!("{:?} {:?}", a, b); // [1, 2, 3] [1, 2, 3] }
fn main() { let a = vec![1, 2, 3]; let b = a; println!("{:?} {:?}", a, b); // Error; use of moved value: `a` }
In the above examples, we are just trying to assign the value of a to b . Almost the same code in both code blocks, but having two different data types. And the second one gives an error. This is because of the Ownership.
What is ownership?
⭐️ Variable bindings have ownership of what they’re bound to. A piece of data can only have one owner at a time. When a binding goes out of scope, Rust will free the bound resources. This is how Rust achieves memory safety.
Ownership (noun)
The act, state, or right of possessing something.
Copy types & move types
⭐️ When assigning a variable binding to another variable binding or when passing it to a function(Without referencing), if its data type is a
-
Copy Type
- Bound resources are made a copy and assign or pass it to the function.
- The ownership state of the original bindings is set to “copied” state.
- Mostly Primitive types
-
Move type
- Bound resources are moved to the new variable binding and we can not access the original variable binding anymore.
- The ownership state of the original bindings is set to “moved” state.
- Non-primitive types
🔎 The functionality of a type is handled by the traits which have been implemented to it. By default, variable bindings have ‘move semantics.’ However, if a type implements
core::marker::Copy trait, it has a 'copy semantics'.
💡 So in the above second example, ownership of the Vec object moves to b and a doesn’t have any ownership to access the resource.
Ownership W3CubDocs
Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector. Therefore, it’s important to understand how ownership works in Rust. In this chapter, we’ll talk about ownership as well as several related features: borrowing, slices, and how Rust lays data out in memory.
What is Ownership
Rust’s central feature is ownership. Although the feature is straightforward to explain, it has deep implications for the rest of the language.
All programs have to manage the way they use a computer’s memory while running. Some languages have garbage collection that constantly looks for no longer used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory. Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks at compile time. None of the ownership features slow down your program while it’s running.
Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the more you’ll be able to naturally develop code that is safe and efficient. Keep at it!
When you understand ownership, you’ll have a solid foundation for understanding the features that make Rust unique. In this chapter, you’ll learn ownership by working through some examples that focus on a very common data structure: strings.
Please read The Stack and the Heap
Ownership Rules
First, let’s take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate them:
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
Variable Scope
A scope begins when a block expression begins, with a { symbol, and ends when the block expression ends, with } (or when a return statement is run before the block reaches its end).
#![allow(unused)] fn main() { // begin of a scope let s = "hello"; } // end of a scope
fn main() { { // s is not valid here, it’s not yet declared let s = "hello"; // s is valid from this point forward // do stuff with s println!("{}", s); } // this scope is now over, and s is no longer valid println!("{}", s); // -> compiler will err // ^ not found in this scope }
In other words, there are two important points in time here:
- When s comes into scope, it is valid.
- It remains valid until it goes out of scope.
The String Type
To illustrate the rules of ownership, we will use a more complex String data type which a stored on the heap.
- data stored on the stack will be popped off the stack when their scope is over.
We’ll use String as the example here and concentrate on the parts of String that relate to ownership. These aspects also apply to other complex data types, whether they are provided by the standard library or created by you. We’ll discuss String in more depth in other area.
We’ve already seen string literals, where a string value is hardcoded into our program. String literals are convenient, but they aren’t suitable for every situation in which we may want to use text. One reason is that they’re immutable. Another is that not every string value can be known when we write our code: for example, what if we want to take user input and store it?
Textual Types
The types char and str hold textual data.
A value of type str is represented the same way as [u8], it is a slice of 8-bit unsigned bytes. However, the Rust standard library makes extra assumptions about str: methods working on str assume and ensure that the data in there is valid UTF-8. Calling a str method with a non-UTF-8 buffer can cause Undefined Behavior now or in the future.
Since str is a dynamically sized type, it can only be instantiated through a pointer type, such as &str.
String
This type is allocated on the heap and as such is able to store an amount of text that is unknown to us at compile time. You can create a String from a string literal using the from function, like so:
#![allow(unused)]
fn main() {
let s = String::from("hello");
}
The double colon (::) is an operator that allows us to namespace this particular from function under the String type rather than using some sort of name like string_from. We’ll discuss this syntax more in the “Method Syntax” section of Chapter 5 and when we talk about namespacing with modules in “Paths for Referring to an Item in the Module Tree” in Chapter 7.
This kind of string can be mutated:
fn main() { let mut s = String::from("hello"); s.push_str(", world!"); // push_str() appends a literal to a String println!("{}", s); // This will print `hello, world!` }
So, what’s the difference here? Why can String be mutated but literals cannot? The difference is how these two types deal with memory.
Memory and Allocation
In the case of a string literal, we know the contents at compile time, so the text is hardcoded directly into the final executable. This is why string literals are fast and efficient. But these properties only come from the string literal’s immutability. Unfortunately, we can’t put a blob of memory into the binary for each piece of text whose size is unknown at compile time and whose size might change while running the program.
With the String type, in order to support a mutable, growable piece of text, we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means:
- The memory must be requested from the memory allocator at runtime.
- We need a way of returning this memory to the allocator when we’re done with our String.
That first part is done by us: when we call String::from, its implementation requests the memory it needs. This is pretty much universal in programming languages.
However, the second part is different. In languages with a garbage collector (GC), the GC keeps track and cleans up memory that isn’t being used anymore, and we don’t need to think about it. Without a GC, it’s our responsibility to identify when memory is no longer being used and call code to explicitly return it, just as we did to request it. Doing this correctly has historically been a difficult programming problem. If we forget, we’ll waste memory. If we do it too early, we’ll have an invalid variable. If we do it twice, that’s a bug too. We need to pair exactly one allocate with exactly one free.
Rust takes a different path: the memory is automatically returned once the variable that owns it goes out of scope. Here’s a version of our scope example,
fn main() {
{
let s = String::from("hello"); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no
// longer valid
}
There is a natural point at which we can return the memory our String needs to the allocator: when s goes out of scope. When a variable goes out of scope, Rust calls a special function for us. This function is called drop, and it’s where the author of String can put the code to return the memory. Rust calls drop automatically at the closing curly bracket.
Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes called Resource Acquisition Is Initialization (RAII). The drop function in Rust will be familiar to you if you’ve used RAII patterns.
Ways Variables and Data Interact: Move
Multiple variables can interact with the same data in different ways in Rust.
A simple i32 example,
fn main() { let x = 5; println!("&x: {:p}", &x); // -> &x: 0x7ffeb6ed4a4c println!("*&x: {}", *&x); // -> *&x: 5 let y = x; println!("&y: {:p}", &y); // -> &y: 0x7ffeb6ed4aec - - 0x7ffeb6ed4a4c = 0xa0 println!("*&y: {}", *&y); // *&y: 5 }
We can probably guess what this is doing: “bind the value 5 to x; then make a copy of the value in x and bind it to y.” We now have two variables, x and y, and both equal 5. This is indeed what is happening, because integers are simple values with a known, fixed size, and these two 5 values are pushed onto the stack.
| Address | Name | Value |
|---|---|---|
| 1 | y | 5 |
| 0 | x | 5 |
A complicated String example,
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait
// if you do
// println!("{}, world!", s1);
// ^^ value borrowed here after move
}
This is what it works under the hoof,
let s1 = String::from("hello");
let s1 = String::from("hello");
Then s1 will be out of scope:
Clone
If we do want to deeply copy the heap data of the String, not just the stack data, we can use a common method called clone.
example of the clone method in action:
fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, s2 = {}", s1, s2); }
This works just fine and explicitly produces the behavior shown in Figure 4-3, where the heap data does get copied.
When you see a call to clone, you know that some arbitrary code is being executed and that code may be expensive. It’s a visual indicator that something different is going on.
Stack-Only Data: Copy
Example,
fn main() { let x = 5; let y = x; println!("x = {}, y = {}", x, y); }
The reason is that types such as integers that have a known size at compile time are stored entirely on the stack, so copies of the actual values are quick to make. That means there’s no reason we would want to prevent x from being valid after we create the variable y. In other words, there’s no difference between deep and shallow copying here, so calling clone wouldn’t do anything different from the usual shallow copying and we can leave it out.
Rust has a special annotation called the Copy trait that we can place on types like integers that are stored on the stack (we’ll talk more about traits in Chapter 10). If a type has the Copy trait, an older variable is still usable after assignment. Rust won’t let us annotate a type with the Copy trait if the type, or any of its parts, has implemented the Drop trait. If the type needs something special to happen when the value goes out of scope and we add the Copy annotation to that type, we’ll get a compile-time error. To learn about how to add the Copy annotation to your type, see “Derivable Traits” in Appendix C.
Here are some of the types that are Copy:
- All the integer types, such as u32.
- The Boolean type, bool, with values true and false.
- All the floating point types, such as f64.
- The character type, char.
- Tuples, if they only contain types that are also Copy. For example, (i32, i32) is Copy, but (i32, String) is not.
Ownership and Functions
The semantics for passing a value to a function are similar to those for assigning a value to a variable. Passing a variable to a function will move or copy, just as assignment does.
fn main() { let s = String::from("hello"); // s comes into scope // // - move occurs because `s` has type `String`, which does not implement the `Copy` trait takes_ownership(s); // - value moved here // s's value moves into the function... and so is no longer valid here // println!("s: {:?}", s); // ^ value borrowed here after move let x = 5; // x comes into scope makes_copy(x); // x would move into the function, // but i32 is Copy, so it’s okay to still // use x afterward println!("x: {:?}", x); } // Here, x goes out of scope, then s. But because s's value was moved, nothing // special happens. fn takes_ownership(some_string: String) { // some_string comes into scope println!("{}", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed. fn makes_copy(some_integer: i32) { // some_integer comes into scope println!("{}", some_integer); } // Here, some_integer goes out of scope. Nothing special happens.
But, this example that I am still confused!!!
fn main() { let s = String::from("hello"); // s comes into scope println!("&s: {:p}", &s); // using pointer &s takes_ownership(&s); println!("s: {:?}", s); let x = 5; // x comes into scope makes_copy(x); // x would move into the function, // but i32 is Copy, so it’s okay to still // use x afterward println!("x: {:?}", x); } // Here, x goes out of scope, then s. But because s's value was moved, nothing // special happens. fn takes_ownership(some_string: &String) { // some_string comes into scope println!("{:p}", some_string); println!("{}", some_string); // some_string = String::from("hello World!") } fn makes_copy(some_integer: i32) { // some_integer comes into scope println!("{}", some_integer); } // Here, some_integer goes out of scope. Nothing special happens.
Return Values and Scope
#[allow(unused_variables)] fn main() { let s1 = gives_ownership(); // gives_ownership moves its return // value into s1 println!("s1: {}", s1); println!("&s1: {:p}", &s1); let s2 = String::from("hello"); // s2 comes into scope let s3 = takes_and_gives_back(s2); // s2 is moved into // takes_and_gives_back, which also // moves its return value into s3 } // Here, s3 goes out of scope and is dropped. s2 goes out of scope but was // moved, so nothing happens. s1 goes out of scope and is dropped. fn gives_ownership() -> String { // gives_ownership will move its // return value into the function // that calls it let some_string = String::from("hello"); // some_string comes into scope println!("some_string: {:p}", &some_string); some_string // some_string is returned and // moves out to the calling // function } // takes_and_gives_back will take a String and return one fn takes_and_gives_back(a_string: String) -> String { // a_string comes into // scope a_string // a_string is returned and moves out to the calling function }
The ownership of a variable follows the same pattern every time: assigning a value to another variable moves it. When a variable that includes data on the heap goes out of scope, the value will be cleaned up by drop unless the data has been moved to be owned by another variable.
Taking ownership and then returning ownership with every function is a bit tedious. What if we want to let a function use a value but not take ownership? It’s quite annoying that anything we pass in also needs to be passed back if we want to use it again, in addition to any data resulting from the body of the function that we might want to return as well.
It’s possible to return multiple values using a tuple, as shown in Listing 4-5.
fn main() { let s1 = String::from("hello"); let (s2, len) = calculate_length(s1); println!("The length of '{}' is {}.", s2, len); } fn calculate_length(s: String) -> (String, usize) { let length = s.len(); // len() returns the length of a String (s, length) }
But this is too much ceremony and a lot of work for a concept that should be common. Luckily for us, Rust has a feature for this concept, called references.
Effective Rust@https://doc.rust-lang.org/1.22.0/book/
So you’ve learned how to write some Rust code. But there’s a difference between writing any Rust code and writing good Rust code.
This chapter consists of relatively independent tutorials which show you how to take your Rust to the next level. Common patterns and standard library features will be introduced. Read these sections in any order of your choosing.
The Stack and the Heap
As a systems language, Rust operates at a low level. If you’re coming from a high-level language, there are some aspects of systems programming that you may not be familiar with. The most important one is how memory works, with a stack and a heap. If you’re familiar with how C-like languages use stack allocation, this chapter will be a refresher. If you’re not, you’ll learn about this more general concept, but with a Rust-y focus.
As with most things, when learning about them, we’ll use a simplified model to start. This lets you get a handle on the basics, without getting bogged down with details which are, for now, irrelevant. The examples we’ll use aren’t 100% accurate, but are representative for the level we’re trying to learn at right now. Once you have the basics down, learning more about how allocators are implemented, virtual memory, and other advanced topics will reveal the leaks in this particular abstraction.
Memory management
These two terms are about memory management. The stack and the heap are abstractions that help you determine when to allocate and deallocate memory.
Here’s a high-level comparison:
- The stack is very fast, and is where memory is allocated in Rust by default. But the allocation is local to a function call, and is limited in size.
- The heap, on the other hand, is slower, and is explicitly allocated by your program. But it’s effectively unlimited in size, and is globally accessible. Note this meaning of heap, which allocates arbitrary-sized blocks of memory in arbitrary order, is quite different from the heap data structure.
The Stack
Let’s talk about this Rust program:
fn main() { let x = 42; }
This program has one variable binding, x. This memory needs to be allocated from somewhere. Rust ‘stack allocates’ by default, which means that basic values ‘go on the stack’. What does that mean?
Well, when a function gets called, some memory gets allocated for all of its local variables and some other information. This is called a stack frame, and for the purpose of this tutorial, we’re going to ignore the extra information and only consider the local variables we’re allocating. So in this case, when main() is run, we’ll allocate a single 32-bit integer for our stack frame. This is automatically handled for you, as you can see; we didn’t have to write any special Rust code or anything.
When the function exits, its stack frame gets deallocated. This happens automatically as well.
That’s all there is for this simple program. The key thing to understand here is that stack allocation is very, very fast. Since we know all the local variables we have ahead of time, we can grab the memory all at once. And since we’ll throw them all away at the same time as well, we can get rid of it very fast too.
The downside is that we can’t keep values around if we need them for longer than a single function. We also haven’t talked about what the word, ‘stack’, means. To do that, we need a slightly more complicated example:
fn foo() { let y = 5; let z = 100; } fn main() { let x = 42; foo(); }
This program has three variables total: two in foo(), one in main(). Just as before, when main() is called, a single integer is allocated for its stack frame. But before we can show what happens when foo() is called, we need to visualize what’s going on with memory. Your operating system presents a view of memory to your program that’s pretty simple: a huge list of addresses, from 0 to a large number, representing how much RAM your computer has. For example, if you have a gigabyte of RAM, your addresses go from 0 to 1,073,741,823. That number comes from (2 ** 30), the number of bytes in a gigabyte.
‘Gigabyte’ can mean two things: (10 ** 09, 1,000,000,000), or (2 ** 30, 102410241024 = 1,073,741,824). The IEC standard resolved this by stating that ‘gigabyte’ is (10 ** 9), and ‘gibibyte’ is ( 2 ** 30). However, very few people use this terminology, and rely on context to differentiate. We follow in that tradition here.
This memory is kind of like a giant array: addresses start at zero and go up to the final number. So here’s a diagram of our first stack frame:
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
We’ve got x located at address 0, with the value 42.
When foo() is called, a new stack frame is allocated:
| Address | Name | Value |
|---|---|---|
| 2 | z | 100 |
| 1 | y | 5 |
| 0 | x | 42 |
Because 0 was taken by the first frame, 1 and 2 are used for foo()’s stack frame. It grows upward, the more functions we call. Notice that we are not taking into account the size of each variable (for example, a 32 bit variable would use the memory addresses from 0 to 3, or 4 bytes).
There are some important things we have to take note of here. The numbers 0, 1, and 2 are all solely for illustrative purposes, and bear no relationship to the address values the computer will use in reality. In particular, the series of addresses are in reality going to be separated by some number of bytes that separate each address, and that separation may even exceed the size of the value being stored.
After foo() is over, its frame is deallocated:
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
And then, after main(), even this last value goes away. Easy!
It’s called a ‘stack’ because it works like a stack of dinner plates: the first plate you put down is the last plate to pick back up. Stacks are sometimes called ‘last in, first out queues’ for this reason, as the last value you put on the stack is the first one you retrieve from it.
Let’s try a three-deep example:
fn italic() { let i = 6; } fn bold() { let a = 5; let b = 100; let c = 1; italic(); } fn main() { let x = 42; bold(); }
Okay, first, we call main():
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
Next up, main() calls bold():
| Address | Name | Value |
|---|---|---|
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
| 0 | x | 42 |
And then bold() calls italic():
| Address | Name | Value |
|---|---|---|
| 4 | i | 6 |
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
| 0 | x | 42 |
Whew! Our stack is growing tall.
After italic() is over, its frame is deallocated, leaving only bold() and main():
| Address | Name | Value |
|---|---|---|
| 3 | c | 1 |
| 2 | b | 100 |
| 1 | a | 5 |
| 0 | x | 42 |
And then bold() ends, leaving only main():
| Address | Name | Value |
|---|---|---|
| 0 | x | 42 |
And then we’re done. Getting the hang of it? It’s like piling up dishes: you add to the top, you take away from the top.
The Heap
Now, this works pretty well, but not everything can work like this. Sometimes, you need to pass some memory between different functions, or keep it alive for longer than a single function’s execution. For this, we can use the heap.
In Rust, you can allocate memory on the heap with the Box<T> type.
⭐ All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box
. A box is a smart pointer to a heap allocated value of type T. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.
⭐ Boxed values can be dereferenced using the * operator; this removes one layer of indirection.
Here’s an example:
fn main() { let x = Box::new(5); let y = 42; }
| Address | Name | Value |
|---|---|---|
| 1 | y | 42 |
| 0 | x | ?????? |
A Box is a special kind of pointer that points to the heap, but it is still a pointer.
Knowing that, you understand that:
- Box
is 8 bytes because i8 is sized, - Box<&[i8]> is 8 bytes because a reference is sized,
- Box<[i8]> is 16 bytes because a slice is unsized.
We allocate space for two variables on the stack. y is 42, as it always has been, but what about x? Well, x is a Box
| Address | Name | Value |
|---|---|---|
| (2 ** 30) -1 | 5 | |
| .... | ... | ... |
| 1 | y | 42 |
| 0 | x | → (2 ** 30) - 1 |
We have (2 ** 30) addresses in our hypothetical computer with 1GB of RAM. And since our stack grows from zero, the easiest place to allocate memory is from the other end. So our first value is at the highest place in memory. And the value of the struct at x has a raw pointer to the place we’ve allocated on the heap, so the value of x is (2 ** 30) - 1, the memory location we’ve asked for.
We haven’t really talked too much about what it actually means to allocate and deallocate memory in these contexts. Getting into very deep detail is out of the scope of this tutorial, but what’s important to point out here is that the heap isn’t a stack that grows from the opposite end. We’ll have an example of this later in the book, but because the heap can be allocated and freed in any order, it can end up with ‘holes’. Here’s a diagram of the memory layout of a program which has been running for a while now:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) -1 | 5 | |
| (2 ** 30) -2 | ||
| (2 ** 30) -3 | ||
| (2 ** 30) -4 | 42 | |
| .... | ... | ... |
| 2 | z | → (2 ** 30) - 4 |
| 1 | y | 42 |
| 0 | x | → (2 ** 30) - 1 |
In this case, we’ve allocated four things on the heap, but deallocated two of them. There’s a gap between (230) - 1 and (230) - 4 which isn’t currently being used. The specific details of how and why this happens depends on what kind of strategy you use to manage the heap. Different programs can use different ‘memory allocators’, which are libraries that manage this for you. Rust programs use jemalloc for this purpose.
Anyway, back to our example. Since this memory is on the heap, it can stay alive longer than the function which allocates the box. In this case, however, it doesn’t.2 When the function is over, we need to free the stack frame for main(). Box<T>, though, has a trick up its sleeve: Drop. The implementation of Drop for Box deallocates the memory that was allocated when it was created. Great! So when x goes away, it first frees the memory allocated on the heap:
| Address | Name | Value |
|---|---|---|
| 1 | y | 42 |
| 0 | x | ?????? |
We can make the memory live longer by transferring ownership, sometimes called ‘moving out of the box’. More complex examples will be covered later.
Arguments and Borrowing
We’ve got some basic examples with the stack and the heap going, but what about function arguments and borrowing? Here’s a small Rust program:
fn foo(i: &i32) { let z = 42; } fn main() { let x = 5; let y = &x; foo(y); }
When we enter main(), memory looks like this:
| Address | Name | Value |
|---|---|---|
| 1 | y | → 0 |
| 0 | x | 5 |
x is a plain old 5, and y is a reference to x. So its value is the memory location that x lives at, which in this case is 0.
What about when we call foo(), passing y as an argument?
| Address | Name | Value |
|---|---|---|
| 3 | z | 42 |
| 2 | i | → 0 |
| 1 | y | → 0 |
| 0 | x | 5 |
Stack frames aren’t only for local bindings, they’re for arguments too. So in this case, we need to have both i, our argument, and z, our local variable binding. i is a copy of the argument, y. Since y’s value is 0, so is i’s.
This is one reason why borrowing a variable doesn’t deallocate any memory: the value of a reference is a pointer to a memory location. If we got rid of the underlying memory, things wouldn’t work very well.
A complex example
fn foo(x: &i32) { let y = 10; let z = &y; baz(z); bar(x, z); } fn bar(a: &i32, b: &i32) { let c = 5; let d = Box::new(5); let e = &d; baz(e); } fn baz(f: &i32) { let g = 100; } fn main() { let h = 3; let i = Box::new(20); let j = &h; foo(j); }
First, we call main():
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| ... | ... | ... |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
We allocate memory for j, i, and h. i is on the heap, and so has a value pointing there.
Next, at the end of main(), foo() gets called:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| ... | ... | ... |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
Space gets allocated for x, y, and z. The argument x has the same value as j, since that’s what we passed it in. It’s a pointer to the 0 address, since j points at h.
Next, foo() calls baz(), passing z:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| ... | ... | ... |
| 7 | g | 100 |
| 6 | f | → 4 |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
We’ve allocated memory for f and g. baz() is very short, so when it’s over, we get rid of its stack frame:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| ... | ... | ... |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
Next, foo() calls bar() with x and z:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| (2 ** 30) - 2 | 5 | |
| ... | ... | ... |
| 10 | e | → 9 |
| 9 | d | → (2** 30) - 2 |
| 8 | c | 5 |
| 7 | b | → 4 |
| 6 | a | → 0 |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
We end up allocating another value on the heap, and so we have to subtract one from (230) - 1. It’s easier to write that than 1,073,741,822. In any case, we set up the variables as usual.
At the end of bar(), it calls baz():
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| (2 ** 30) - 2 | 5 | |
| ... | ... | ... |
| 12 | g | 100 |
| 11 | f | → (2 ** 30) - 2 |
| 10 | e | → 9 |
| 9 | d | → (2** 30) - 2 |
| 8 | c | 5 |
| 7 | b | → 4 |
| 6 | a | → 0 |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
With this, we’re at our deepest point! Whew! Congrats for following along this far.
After baz() is over, we get rid of f and g:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| (2 ** 30) - 2 | 5 | |
| ... | ... | ... |
| 10 | e | → 9 |
| 9 | d | → (2** 30) - 2 |
| 8 | c | 5 |
| 7 | b | → 4 |
| 6 | a | → 0 |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
Next, we return from bar(). d in this case is a Box
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| ... | ... | ... |
| 5 | z | → 4 |
| 4 | y | 10 |
| 3 | x | → 0 |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
And after that, foo() returns:
| Address | Name | Value |
|---|---|---|
| (2 ** 30) - 1 | 20 | |
| ... | ... | ... |
| 2 | j | → 0 |
| 1 | i | → (2 ** 30) - 1 |
| 0 | h | 3 |
What do other languages do?
Most languages with a garbage collector heap-allocate by default. This means that every value is boxed. There are a number of reasons why this is done, but they’re out of scope for this tutorial. There are some possible optimizations that don’t make it true 100% of the time, too. Rather than relying on the stack and Drop to clean up memory, the garbage collector deals with the heap instead.
Which to use?
So if the stack is faster and easier to manage, why do we need the heap? A big reason is that Stack-allocation alone means you only have 'Last In First Out (LIFO)' semantics for reclaiming storage. Heap-allocation is strictly more general, allowing storage to be taken from and returned to the pool in arbitrary order, but at a complexity cost.
Generally, you should prefer stack allocation, and so, Rust stack-allocates by default. The LIFO model of the stack is simpler, at a fundamental level. This has two big impacts: runtime efficiency and semantic impact.
Runtime Efficiency
Managing the memory for the stack is trivial: The machine increments or decrements a single value, the so-called “stack pointer”. Managing memory for the heap is non-trivial: heap-allocated memory is freed at arbitrary points, and each block of heap-allocated memory can be of arbitrary size, so the memory manager must generally work much harder to identify memory for reuse.
If you’d like to dive into this topic in greater detail, this paper is a great introduction.
Semantic impact
Stack-allocation impacts the Rust language itself, and thus the developer’s mental model. The LIFO semantics is what drives how the Rust language handles automatic memory management. Even the deallocation of a uniquely-owned heap-allocated box can be driven by the stack-based LIFO semantics, as discussed throughout this chapter. The flexibility (i.e. expressiveness) of non LIFO-semantics means that in general the compiler cannot automatically infer at compile-time where memory should be freed; it has to rely on dynamic protocols, potentially from outside the language itself, to drive deallocation (reference counting, as used by Rc<T> and Arc<T>, is one example of this).
When taken to the extreme, the increased expressive power of heap allocation comes at the cost of either significant runtime support (e.g. in the form of a garbage collector) or significant programmer effort (in the form of explicit memory management calls that require verification not provided by the Rust compiler).
mdbook
mongoDB Rust Driver
Quick Start
¶Step 1. Create a Project Directory
- from ~/mdbook-proj/learn-rust-dumindu-madunuwan/src/mongodb
$ cargo new rust_quickstart
Creating binary (application) `rust_quickstart` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
$ tree rust_quickstart/
rust_quickstart/
├── Cargo.toml
└── src
└── main.rs
¶Step 2. Cargo.toml
- Asynchronous
[package]
name = "rust_quickstart"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = "1.0.188"
futures = "0.3.28"
tokio = {version = "1.32.0", features = ["full"]}
[dependencies.mongodb]
version = "2.8.2"
features = ["tokio-runtime"]
- synchronous
[package]
name = "rust_quickstart"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = "1.0.188"
[dependencies.mongodb]
version = "2.8.2"
features = ["tokio-sync"]