Rust

home https://www.rust-lang.org/
wiki https://en.wikipedia.org/wiki/Rust_(programming_language)
research https://research.mozilla.org/rust/
gitorg https://github.com/Rust-Lang
packages https://crates.io/

Language

fn main() {
    println!("Hello, World!");
}
  • multiple pass compiler
  • there is no truthiness in Rust, only booleans
  • panic!() - an unrecoverable error
  • todo!()
  • unreachable!()
  • Rust, use range for loops
    • 0..10
    • 0..=10
  • Editions

    2015 1.00
    2018 1.31
    2021 1.56
    2024 1.85

variables

let x: u8 = 1;
let mut x = 10; // ~mutability~, when a variable can be changed
let x = 2;  //    - ~shadowing~, if are the same type, although effectively are different variables
let x = 10;

import / export

use supper:**; // import all files on project

string interpolation format

see: println!() format!() panic!()

format string description
r#""raw"\tlines\n"#  
b"this string of ASCII bytes"  
\u{D589} unicode printing
{:p} pointer
{:b} {:x} {:o} binary, hexa, and octal
{0} {1} order of arguments
{foo} {bar} name of arguments
{} {:?} {:#?} pretty printer
{var:pad align min.max}  

operator

-> skinny arrow, on fn definitions
{} code blocks, return a value
! denote macro names
? try operator
== structural equality

attributes #[]

  • derive(Debug)

functions

Expressions = something that evaluates to a value Statement = does NOT evaluate to a value end with a (;)

fn beta(MyStruct {y,z,..}: MyStruct) -> i32 // struct destructuring
fn beta() -> i32 {
  8 // expression
  // return 8;  // statement, same but less idiomatic
  // 8;         // with the ";" it will return "()"
}

Style

https://github.com/rust-lang/rust/tree/HEAD/src/doc/style-guide/src

  • 4 spaces of identation
  UpperCamelCase snake_case lowercase
Implementation YES    
Struct YES    
Enum YES    
Variables   YES  
Functions   YES  
Native Types     YES

Types

Option & Result

enum Option<T> {
  Some(T),
  None,
}
enum Result<T,E> {
  Ok(T),
  Err(E),
}

Primitive

  • as is used for casting (compiler allows demotion)
    • true as u8 // = 1
  • division by zero
    • integers = panic!
    • floats = infinity
  • std::i8::MIN or i8::MIN
  • std::i8::MAX or i8::MAX
TYPE EX DESCRIPTION
i/u[NN]   where NN is 8,16,32,64,128
u8 1u8  
i32 1_000 default literal
i64 ?  
f32 ?  
f64 5. default literal
isize 10 arch dep size
usize 10 arch dep size, used for indexing
char 'a' up to 4 bytes, same as u32
bool true false implemented as an u8
String String::from("foo") .pop()
&str "foo"  
  • tuple, array
    • stack (aka size known at compile time)
  • vector
    • heap
    • address/length/capacity (usize x3)
  • String
    • heap allocated
    • mutable
    • has: prt, len, cap
  • &str
    • points to a squence of UTF-8 chars (a view into a String)
    • immutable
    • analogous to &[u8]
    • has: ptr, len

Compound

name create access destructure insert type
unit (any statement) NO () NO ()
tuple (5,2) .0 (a,_b) NO (i64,i64)
unit struct SName NO NO NO struct SN
tuple struct SName(1,2) .0 SName(a,b) NO struct SN(i8,i8)
named struct SName{a: 10} .FIELD SName{a, ..} NO struct SN {x: i64}
HashMap HashMap::new() .get(key) (key,val) .insert(key, val)  
array [1,2] [0] [a,_,_] NO [i32;LENGTH]
vec(tors) vec![1,2] [0] .get(0)   .push(23) Vec<i32>
  Vec::new()        
  Vec::from([1,2])        
  Vec::with_capacity(N)        
  • structs
    • support punning on creation
  • no memory overhead for tuple/array/struct
  • unit
    • a special case of an empty tuple
    • come up for functions that return no values
    • aka "void" in c
    • sometimes used as Err(())

enum

  • can be imported with use ENUMNAME::*
  • each member gets a number from 0 to 10 (can be given different numbers)
  • they can optionally have a payload in the form of a record or a tuple
type create match
enum Color { Green, Red, Blue } Color::Green Color::Red
enum Color { Green = 10, Blue = 20 } Color::Green  
enum Color { Red, Custom{ r:u8,g:u8 }} Color::Custom {r: 8, g: 2} Color::Custom {r, g}
enum Color { Red, Custom(u8,u8) } Color::Custom(10,20) Color::Custom(a,b)

control flow

if foo > 1 {} else if foo < 0 {} else {} // expression
if let MyStruct { x, .. } = foostruct {..} // if-let, non exhaustive
match ptr {
    Some(ptr) => ptr.g(),
    None      => {}
    // _ => println!("catch all pattern")
}

loops

for num in nums {}
while let Some(i) = optional {..} // alternative to loop+match
loop{} // for infinite loop

struct + impl(ementation) (aka methods)

  is sugar for…
self self: Self
&self self: &Self
&mut self self: &mut Self
struct Foo { // can be an enum
      x: usize
  pub y: usize
}
impl Foo {
        fn new0(x: usize) -> Self // static method
        fn this()         //        static method
    pub fn this()         // public static method
        fn this(&self)    //      instance method
        fn this(&mut self)
    pub fn this(self)     // takes the self itself
}

struct + impl + generic

struct MyVect<T> {
    contents: T,
}
impl<T> MyVect<T> {
    pub fn find<P>(&self, predicate: P) -> Option<&T>
    where P: Fn(&T) -> bool {
        for v in self {
            if predicate(v) {
                return Some(v);
            }
        }
        None
    }
}

trait + impl

a common method for multiple types

trait Foo { // like an interface
    fn method(&self) -> retType;
}
impl Foo for MyStruct {
    fn method(&self) -> retType {...}
}

Standard Library

https://doc.rust-lang.org/std/#modules

MODULE DESCRIPTION
array Utilities for the array primitive type.
char Utilities for the char primitive type.
f32 Constants for the f32 single-precision floating point type.
f64 Constants for the f64 double-precision floating point type.
slice Utilities for the slice primitive type.
str Utilities for the str primitive type.
string A UTF-8–encoded, growable string.
alloc Memory allocation APIs.
any Utilities for dynamic typing or type reflection.
arch SIMD and vendor intrinsics module.
ascii Operations on ASCII strings and characters.
backtrace Support for capturing a stack backtrace of an OS thread
borrow A module for working with borrowed data.
boxed The Box<T> type for heap allocation.
cell Shareable mutable containers.
clone The Clone trait for types that cannot be ‘implicitly copied’.
cmp Utilities for comparing and ordering values.
collections Collection types.
convert Traits for conversions between types.
default The Default trait for types with a default value.
env Inspection and manipulation of the process’s environment.
error Interfaces for working with Errors.
ffi Utilities related to FFI bindings.
fmt Utilities for formatting and printing Strings.
fs Filesystem manipulation operations.
future Asynchronous basic functionality.
hash Generic hashing support.
hint Hints to compiler that affects how code should be emitted or optimized. Hints may be compile time or runtime.
io Traits, helpers, and type definitions for core I/O functionality.
iter Composable external iteration.
marker Primitive traits and types representing basic properties of types.
mem Basic functions for dealing with memory.
net Networking primitives for TCP/UDP communication.
num Additional functionality for numerics.
ops Overloadable operators.
option Optional values.
os OS-specific functionality.
panic Panic support in the standard library.
path Cross-platform path manipulation.
pin Types that pin data to a location in memory.
prelude The Rust Prelude
primitive This module reexports the primitive types to allow usage that is not possibly shadowed by other declared types.
process A module for working with processes.
ptr Manually manage memory through raw pointers.
rc Single-threaded reference-counting pointers. ‘Rc’ stands for ‘Reference Counted’.
result Error handling with the Result type.
sync Useful synchronization primitives.
task Types and Traits for working with asynchronous tasks.
thread Native threads.
time Temporal quantification.
vec A contiguous growable array type with heap-allocated contents, written Vec<T>.

Experimental Modules

assert_matches Unstable module containing the unstable assert_matches macro.
async_iter Composable asynchronous iteration.
f16 Constants for the f16 double-precision floating point type.
f128 Constants for the f128 double-precision floating point type.
intrinsics Compiler intrinsics.
pat Helper module for exporting the pattern_type macro
simd Portable SIMD module.

Codebases


Created: 2020-01-01

Updated: 2024-11-16

Back