Functions
Last updated
Last updated
Declare function using fn
, reference:
Rust code uses snake case as the conventional style for function and variable names.
In function signatures, you must declare the type of each parameter.
When defining multiple parameters, separate the parameter declarations with commas.
Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow ->
.
Rust have statements and expressions:
Statements are instructions that perform some action and do not return a value.
Expressions evaluate to a resultant value. Let’s look at some examples.
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.
You can return early from a function by using the return
keyword and specifying a value, but most functions return the last expression implicitly.
Reference:
We just need to add a new function called call_me
without any return value.
Rust code uses snake case as the conventional style for function and variable names, in which all letters are lowercase and underscores separate words.
In function signatures, you must declare the type of each parameter.
This is a deliberate decision in Rust’s design: requiring type annotations in function definitions means the compiler almost never needs you to use them elsewhere in the code to figure out what type you mean. The compiler is also able to give more helpful error messages if it knows what types the function expects.
When defining multiple parameters, separate the parameter declarations with commas.
So we just need to add i32
as the arguments/parameter type.
call_me
function expect an argument/parameter, add 5
as parameter since the function expect type u8
.
Functions can return values to the code that calls them. We don’t name return values, but we must declare their type after an arrow ->
.
In this exercise we just need to add return type as i64
.
Rust have statements and expressions:
Statements are instructions that perform some action and do not return a value.
Expressions evaluate to a resultant value. Let’s look at some examples.
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.
You can return early from a function by using the return keyword and specifying a value, but most functions return the last expression implicitly.
In this exercise the square
functions expect a return value, but the function body only have one line statement. By removing the semicolon ;
we make it as an expression and will return the value of num * num
Reference: