rust
i've started learning rust, and it's been fun and eye-opening. below are just my notes from the docs, or from other resources.
cargo
- build system and package manager
create cargo
build, run or check cargo
- produces an exec file
- compiles and run exec in one cmd
- checks to make sure code still compiles, doesn't produce exec
cargo lock
- cargo lock ensures reproducibility - locks dependencies versions
variables and mutability
-
to make a variable mutable use
mut
after let -
to make a constant use
const <var_name>: <data_type> = ...
-
use ALL CAPS for const (naming convention)
shadowing
- a variable can be shadowed by the second (same var name)
- have to use
let
again. - using
let
means that we can do transformation on that variable, then it becomes immutable again.
data types
-
scalar types: represents single value
- integers, floating-point nums, booleans and characters
- 8-bit: i8, u8
- 16-bit: i16, u16
- 32-bit: i32, u32
- 64-bit: i64, u64
- 128-bit: i128, u128,
- arch: isize, usize
-
integer overflow: rust will "panic" at runtime if overflow occurs.to handle possibility of overflow you can wrap all modes with
wrapping_*
methods, return None if overflow usingchecked_*
method, return val and boolean indicating whether there was overflow usingoverflowing_*
methods, or saturate the value's min or max values withsaturing_*
methods -
floating point types: represents num with decimal values
- f32 or f64
-
booleans:
true
,false
-
char: use single quotes
''
compounds types
-
tuples:
let tup: (<data type>, <data type>, <data type>, ...) = (...,...,...)
- access tuples using
tup.0
,tup.<index>
- access tuples using
-
array: arrays have fixed length in rust
- access arrays using
a[<index>]
- access arrays using
functions
- this gives "Another function", "Value of x is 5", and y=4
- notice how the inside the block there is no seimicolon, if there is a semicolon it becomes a statement, and wont return a value.
functions with return values
- the above has no parameters and defines the type of return value, no semicolon as we don't want it to be a statement, but rather a return value
control flow
- use if, else like other languages
- but can also do same line (same data type) let if
- three types of loops: loop, while and for
- loop is infinitely running, unless told to stop
- a loop is to retry operation that might fail, like checking if a thread has completed its job
- you can also have loop labels (what the heck!)
citations: https://doc.rust-lang.org/book/