rust
Local Documentation
rustup doc
brings up all the local documentation including- The Rust book
- Rust by Example
- Cargo book
- Inside your project,
cargo doc --open
opens your project's documentation- Without
--open
will just generate the documentation, which can be potentially shared with others as required.
- Without
Data Types
- Arrays : Fixed size
- When defining say days of the week, months of the year etc.
- Initialize as :
let a = [3; 5];
is same aslet a = [3, 3, 3, 3, 3];
- Vector : Like array but can shrink and/or grow
- If unsure, use Vector
Control Flow
rust does not have
truthy
values. e.g. ifx
is1
, thenif x
does not compile.x
must be booleanloop
can have optional label. See the documentation
'outer: loop {
. ...
loop { // inner, unlabeled loop
...
if some_condition {
break; // Will break from inner/unlabeled loop
}
...
...
if some_other_condition {
break 'outer'; // will break out of the outer loop
}
...
}
}
Statements Vs Expressions
Statements do not return a value, expressions do.
C and Ruby, where the assignment returns the value of the assignment.
In those languages, you can write x = y = 6 and have both x and y have
the value 6; that is not the case in Rust.
In a function, last expression is also a return value.
If you add a semicolon to the end of an expression, you turn it into
a statement, and it will then not return a value.
Ownership
- Cloning avoids Moves
- Useful when we need to reference the "original" data after it the ownership is moved
.clone
create a copy (which is used to move the oownership,leaving the original intact)
Slice
We create slices using a range within brackets by specifying
[starting_index..ending_index]
, wherestarting_index
is the first position
in the slice andending_index
is one more than the last position in the slice.