LGR Cheat Sheet
LGR Cheat Sheet
Table of Contents
Signed integers
// Instantiation
i8, i16, i32, i64, i128
let user1 = User {
username: String::from("bogdan"),
Floating point numbers
active: true,
f32, f64
};
let x = 5; if counter == 10 {
let x = x * 2; break counter;
}
Type alias };
// `NanoSecond` is a new name for `u64`.
type NanoSecond = u64; while and while let
while n < 101 {
Control Flow n += 1;
}
if and if let
let num = Some(22); let mut optional = Some(0);
Borrowing fn main() {
let x = 5;
Ownership rules takes_copy(x); // x is copied by value
1. Each value in Rust has a variable that’s called its
owner. let s = String::from("Let’s Get Rusty!");
2. There can only be one owner at a time. // s is moved into the function
3. When the owner goes out of scope, the value will takes_ownership(s);
be dropped.
// return value is moved into s1
Borrowing rules let s1 = gives_ownership();
1. At any given time, you can have either one
mutable reference or any number of immutable let s2 = String::from("LGR");
references. let s3 = takes_and_gives_back(s2);
2. References must always be valid. }
Raw pointers
Creating a new package with a library crate
let mut num = 5;
$ cargo new my-project --lib
// immutable raw pointer
let r1 = &num as *const i32;
// mutable raw pointer Defining and using modules
let r2 = &mut num as *mut i32; fn some_function() {}