kieran

Kieran‘s Blog

The world will be better?
github

Comprehensive Rust Tutorial

Day 1: Morning#

1. What is Rust#

Rust is a statically compiled language with similar functionality to cpp.

  • rustc uses LLVM as its backend.
  • Rust and cpp are suitable for similar scenarios.
    • Extremely high flexibility.
    • High level of control.
    • Can be scaled down to very constrained devices such as microcontrollers.
    • No runtime and garbage collection.
    • Focuses on program reliability and safety without sacrificing any performance.

2. Why choose Rust#

Some unique features of Rust:

  • Compiler memory safety.
  • No runtime undefined behavior.
  • Modern programming language features.

2.1 Compile-time guarantees#

Compile-time static memory management:

  • No uninitialized variables.
  • No memory leaks.
  • No "double free".
  • No "use after free".
  • No NULL pointers.
  • No forgotten mutexes.
  • No data races between threads.
  • No iterator invalidation.

2.2 Runtime guarantees#

Rust has no runtime undefined behavior:

  • Array access has boundary checks.
  • Integer overflow is defined (panic or wrap-around).

2.3 Modern features#

Language features:

  • Enums and pattern matching.
  • Generics.
  • Zero-cost abstractions for FFI.
  • Zero-cost abstractions.

Tools:

  • Powerful compiler error messages.
  • Built-in dependency manager.
  • Built-in support for unit tests.
  • Excellent implementation of the Language Server Protocol.

3. Basic syntax#

3.1 Scalar types#

TypeLiterals
Signed integersi8i16i32i64i128isize-1001_000123_i64
Unsigned integersu8u16u32u64u128usize012310_u16
Floating-point numbersf32f643.14-10.0e202_f32
Strings&str"foo""two\nlines"
Unicode scalar typeschar'a''α''∞'
Booleansbooltruefalse
The space occupied by each type is:
  • iNuN, and fN occupy N bits,
  • isize and usize occupy space equal to the size of a pointer,
  • char is 32 bits wide,
  • bool is 8 bits wide.

3.2 Compound types#

TypeLiterals
Arrays[T; N][20, 30, 40][0; 3]
Tuples()(T,)(T1, T2), …()('x',)('x', 1.2), …
Assignment and access of arrays:
fn main() {
	let mut a: [i8; 10] = [42; 10];
	a[5] = 0;
	println!("a: {:?}", a);
}

Assignment and access of tuples:

fn main() {
    let t: (i8, bool) = (7, true);
    println!("t.0: {:?}", t.0);
    println!("t.1: {:?}", t.1);
}

3.3 References#

Rust also provides reference types.

fn main() {
    let mut x: i32 = 10;
    let ref_x: &mut i32 = &mut x;
    *ref_x = 20;
    println!("x: {x}");
}

Note the difference between let mut ref_x: &i32 and let ref_x: &mut i32, the former declares a mutable reference where we can modify the value it is bound to, while the latter declares a reference to a mutable variable.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.