Syntax Flashcards
Anatomy of a function
fn main(){
}
fn fun(x: x32, y: String){ }
What is an exclamation mark after a function name in Rust?
It means you are calling a macro, for example the println!(“bla”) function.
Retrieve a function of a type
the :: syntax.
String::new(), new is a function of the associated type String.
Variables
With ‘let’
let guess = String::new();
Types are implicit
Variables are immutable by default.
Add ‘mut’ after let to make it mutable.
let mut guess = String::new();
Comparison of numbers is awesome! How does it look again?
Use the match construct with pattern matching!
match guess.cmp(&secret_number) {
Ordering::Less => println!(“Too small”),
Ordering::Greater => println!(“Yoo big”),
Ordering::Equal => println!(“You win!”),
}
.cmp can be called on anything that can be compared.
What are continue and break?
When continue is encountered, the current iteration is terminated, returning control to the loop head, typically continuing with the next iteration.
When break is encountered, execution of the associated loop body is immediately terminated.
as vs from
as is known to the compiler and only valid for certain transformations, it can do certain types of more complicated transformations.
From is a trait, which means that any programmer can implement it for their own types and it is thus able to be applied in more situations. It pairs with Into. TryFrom and TryInto have been stable since Rust 1.34.
Apparently, in many cases.. ‘from’ is safer since it’s only implemented for lossless conversions while ‘as’ is implemented for lossy conversions, e.g. you can convert a float to an int with as, not with from.
Anatomy of an array declaration (although you will barely use arrays, example use: months of the year)
let a: [i32: 5] = [1, 2, 3, 4, 5] // so: let name: [type, length] = .. value ..
Anatomy of a loop
loop, while and for.
loop { println!("again!"); // break, continue, break can be followed by an expression to return a value. }
e.g. let result = loop { if counter == 10 { // first counter intuitive thing to me, this SETS the result to counter * 2 and is therefore // a statement, not an expression (hence the semicolon) break counter * 2; } }