Most of the examples are from The Rust Programming Language.
0 Introduction
hello_world.rs
fn main() {
println!("Hello World");
}Function: specify the types of arguments and return value.
fn square(num: i32) -> i32 {
num * num
}1 Variable and Primitive Types
- Immutable variable
let x = 5;
println!("x has the value {x}");- Specify the type explicitly
let x: i32 = 10;- Mutable variable
let mut x = 3;
x = 5;- Compile time constant
const NUMBER: i32 = 3;- Primitive types
- Integer
- Types:
i/u+8/16/32/64/128andisize, usize - Literals
- Decimal
98_222 - Hex
0xff - Octal
0o77 - Binary
0b1111_0000 - Byte (u8, ASCII)
b'A'
- Decimal
- Overflow
- Panic in the debug mode
- Two’s complement wrapping (e.g. for
u8) in the release mode
- Types:
- Char: 4 bytes, Unicode.
- Tuple:
- Create
- Destructure
- Access one particular element via period
. - The tuple without any values is called a unit
(). It represents an empty return type or value. Expressions without an explicit return statement return a unit.
Rust let tup: (i32, f64, u8) = (500, 6.4, 1); let (x, y, z) = tup; let y2 = tup.1; - Array
- Initialize with a comma-separated list inside square bracket.
- Initialize with an initial value and a length, separated by a semicolon.
- Index out of bounds will trigger a runtime error.
Rust let a = [1, 1, 1, 1, 1]; let b = [1; 5];
2 Selection and Iteration Structure
If Expression:
let identifier = if animal == "crab" {
1
} else if animal == "gopher" {
2
} else {
3
};Loops:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}Loop labels to disambiguate between multiple loops
'label: loop {
// ...
break 'label;
}while: conditional loops
while number != 0 {
number -= 1;
}for: loop through a collection
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}For: loop with a range
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
}3 Ownership and Reference
- Mutable and immutable references
- To avoid data race among multiple references, only one of the following cases are allowed at any time:
- one mutable reference
- multiple immutable references
- Dangling references are detected by the compiler.
- To avoid data race among multiple references, only one of the following cases are allowed at any time:
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
// immutable reference
println!("The length of '{s1}' is {len}.");
}
fn calculate_length(s: &String) -> usize {
s.len()
}fn main() {
let mut s = String::from("hello");
change(&mut s); // mutable reference
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}- Slice is a reference to a continuous part of a collection.
- String Slice
&str:&s[l..r]. Both l and r can be omitted if started or ended at the endpoint. - String literals are as slices. For example, in the statement
let s = "Hello", s is a&strtype.
- String Slice
4 Struct
-
Define a struct
- A struct name describes the significance of the pieces of data grouped together.
- Inside the curly brackets, we defined the types and names of the pieces of data, which we called fields.
Rust struct User { active: bool, username: String, email: String, sign_in_count: u64, } -
We create an instance by stating the name of the struct and then add curly brackets containing key-value pairs.
Rust fn main() { let user1 = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; } -
Field Init Shorthand. If the field we are initializing has the same name as the variable that we assign to it, the duplicate
name: namecan be replaced by simply aname. -
It is not allowed to mark some fields as mutable.
mutcan only be specified when creating the instance. -
Creating instances from other instances with struct update syntax.
Rust let user2 = User { email: String::from("another@example.com"), ..user1 // other fields same as user1 }; -
Tuple structs are used when you want to add meanings to tuples.
Rust struct Color(i32, i32, i32); struct Point(i32, i32, i32); fn main() { let black = Color(0, 0, 0); let origin = Point(0, 0, 0); } -
Unit-like structs are useful when you need to implement a trait but don’t want to store any data in the type itself.
Rust struct AlwaysEqual; fn main() { let subject = AlwaysEqual; } -
If a field is not owned by the struct, you must use a lifetime specifier. More about this in later sections.
-
Derive traits.
- If you want to print a structure, you can use
{:?}or{:#?}(for pretty-print). But you have to derive the debug trait first#[derive(Debug)].
Rust #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {rect1:?}"); }- Another way is to use
dbg!macro. The difference is it will takes the ownership of the expression, print the message to thestderr, and return the expression.
Rust #[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let scale = 2; let rect1 = Rectangle { width: dbg!(30 * scale), height: 50, }; dbg!(&rect1); }The output looks like this:
代码 [src/main.rs:10:16] 30 * scale = 60 [src/main.rs:14:5] &rect1 = Rectangle { width: 60, height: 50, } - If you want to print a structure, you can use
-
Methods of a structure.
Rust struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }-
Automatic referencing and dereferencing. Rust doesn’t have an equivalent to
->in C/C++; instead, it automatically adds in&,&mutor*soobjectmatches the signature of the method. It works since methods specify the type ofself, as reading&self, mutating&mut self, or consumingself. -
We can define associated functions (functions in the
impl) that don’t haveselfas their first parameter (thus they are not methods).
Rust impl Rectangle { fn square(size: u32) -> Self { Self { width: size, height: size, } } } // in main: let sq = Rectangle::square(3); -
5 Enums and Pattern Matching
Enumerations (Enums) allow you define a type by enumerating all its possible variants.
- Define and use an enum.
enum IpAddrKind {
V4,
V6,
}
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;- You can put data directly into each enum variant.
enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));- Each variant can have different types and amounts of associated data.
enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));- The
Optionenum: it has advantages over null values.
enum Option<T> {
None,
Some(T),
}- It is so useful that it is included in the prelude (rust’s standard library that is implicitly imported into every Rust program).
- Its variants are also in the prelude, so you can use
SomeandNonedirectly. - For the example below, you must specify a type for
None.
let some_number = Some(5); // Option<i32>
let some_char = Some('e'); // Option<char>
let absent_number: Option<i32> = None;- The
matchcontrol flow construct
matchkeyword followed by an expression, then match arms. Each arm has two parts: a pattern and some code.- It compares the expression with each pattern in order.
- The comma following the arm is optional if you use curly brackets
=> {..}.
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}- Pattern that bind to values:
#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {state:?}!");
25
}
}
}- An example of matching with
Option<T>
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);matchmust be exhaustive (cover all possible cases)._is a special pattern when we want a catch-all but don’t want to use the value.if let, a “syntax sugar”
let mut count = 0;
match coin {
Coin::Quarter(state) => println!("State quarter from {state:?}!"),
_ => count += 1,
}
// Equal to
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!("State quarter from {state:?}!");
} else {
count += 1;
}6 Packages, Crates and Modules
7 Common Collections
- Vectors
- Create
let v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];- Update
let mut v = Vec::new();
v.push(5);- Read an element: it’s better to use
.getto avoid out of bounds.
let v2: i32 = &v[2]; // panic if out of bound
let third: Option<&i32> = v.get(2);- Iterate
let v = vec![1, 2, 3];
for i in &v {
println!("{i}");
}
let mut v = vec![1, 2, 3];
for i in &mut v {
*i += 10; // deferencing
}-
String. String is implemented as a wrapper around a vector of bytes with some extra guarantees, restrictions and capabilities.
- Basic operations:
let mut s = String::new(); // create an empty String
s.push('C'); // push like a vector
let mut s1 = String::from("foo");
let s2 = "bar";
s1.push_str(s2);
// will not take the ownership of s2,
// and the content of s2 will be copied- Add operation: the first operand will be moved, and the second operand should be a
&str.
fn main() {
let mut s1 = String::from("Hello");
let s2 = String::from("World");
let s3 = s1 + &s2;
// s1 moved to s3
println!("s3 = {s3}");
}
format!macro: a convenient way to create a new string
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{s1}-{s2}-{s3}"); // all are copies- Iterate:
.char()or.bytes()
for c in "Зд".chars() {
println!("{c}");
} // З д
for b in "Зд".bytes() {
println!("{b}");
} // 208 151 208 180