L1 - Beginner
Understanding function
Understanding functions syntax
- Functions are declared using
fn
keyword - Use snake case for function names, e.g.,
say_hello
(recommended) - A function can be declared after using it, so order is not important, like JavaScript
- We don't have named parameters, so order is important when passing the parameters
Simple function
fn main() { say_hello()}
fn say_hello() { let message = "hello world"; println!("{}", message);}
Function parameters
- Return type is denoted by
->
fn main() { let result = add_both(2, 5); println!("Result: {}", result)}
fn add_both(a: i32, b: i32) -> i32 { return a + b;}
Tail expression (Shorthand)
- If you leave
;
off the last expression of a block, then it will be returned as the value of the block.
fn main() { let result = add_both(2, 5); println!("Result: {}", result)}
fn add_both(a: i32, b: i32) -> i32 { a + b}
Macros
- They look like function
- Macros accept variable number of arguments
- Name of macro ends with
!
println!
is a macro