Syntax Flashcards

1
Q

Anatomy of a function

A

fn main(){

}

fn fun(x: x32, y: String){
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an exclamation mark after a function name in Rust?

A

It means you are calling a macro, for example the println!(“bla”) function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Retrieve a function of a type

A

the :: syntax.

String::new(), new is a function of the associated type String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Variables

A

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();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Comparison of numbers is awesome! How does it look again?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are continue and break?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

as vs from

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Anatomy of an array declaration (although you will barely use arrays, example use: months of the year)

A

let a: [i32: 5] = [1, 2, 3, 4, 5] // so: let name: [type, length] = .. value ..

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Anatomy of a loop

A

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; 
 }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly