Like every other programming language, Rust has its own rules for declaring functions. Some syntax may seem familiar; however, there are some extra things to notice:
fn
keywordThis keyword is placed before the name of the new function to indicate that a new function is being declared:
fn foo(){
// Do something.
}
Curly braces {}
are used to indicate the function’s body, like most other languages.
All the parameters of a Rust function must have their types declared in the function’s signature:
fn foo(a: i8, b: i8){
// Both 'a' and 'b' are of type i8.
}
The return
keyword can be used to return a value inside a function’s body. When this keyword isn’t used, the last expression is implicitly considered to be the return value. If a function returns a value, its return type is specified in the signature using ->
after the parentheses ()
.
Statement vs. Expression
- A statement does not return a value, so it cannot be used to assign a value to another variable. For example, in some languages, we may be allowed to write
x = y = 5
; but in Rust,let x = (let y = 5)
is an invalid statement because thelet y = 5
statement does not return a value that can be assigned tox
.- Expressions can be a part of a statement.
- When a semi-colon is written at the end of an expression, it turns into a statement and does not return a value.
{}
blocks and function calls are expressions.
fn main() {let a = 10;println!("a = {}", foo(a));}fn foo(a: i8) -> i8 {if a > 0 {return 5;}else {a + 1}}
Free Resources