Recall & Review
beginner Click to reveal answer
What is the basic syntax to declare a function in Rust?
In Rust, a function is declared using the
Example:
fn keyword, followed by the function name, parentheses for parameters, and curly braces for the body.Example:
fn greet() {
println!("Hello!");
}beginner Click to reveal answer
How do you declare a function that takes parameters in Rust?
You list parameters inside the parentheses with their names and types.
Example:
This function takes two 32-bit integers and returns their sum.
Example:
fn add(a: i32, b: i32) -> i32 {
a + b
}This function takes two 32-bit integers and returns their sum.
beginner Click to reveal answer
What does the arrow
-> mean in a Rust function declaration?The arrow
Example:
This means the function returns an
-> indicates the return type of the function.Example:
fn square(x: i32) -> i32 {
x * x
}This means the function returns an
i32 value.beginner Click to reveal answer
How do you return a value from a Rust function?
In Rust, the last expression in the function is returned automatically if it has no semicolon.
Example:
You can also use the
Example:
fn double(x: i32) -> i32 {
x * 2 // returned because no semicolon
}You can also use the
return keyword explicitly.beginner Click to reveal answer
Can Rust functions have no return value? How is it declared?
Yes, functions that do not return a value have the return type
Example:
This function returns nothing (unit).
(), called the unit type.Example:
fn say_hello() {
println!("Hello!");
}This function returns nothing (unit).
What keyword starts a function declaration in Rust?
✗ Incorrect
Rust uses
fn to declare functions.How do you specify the return type of a function in Rust?
✗ Incorrect
The return type is specified after the parameters with
->.What happens if the last expression in a Rust function has no semicolon?
✗ Incorrect
The last expression without a semicolon is returned automatically.
How do you declare a function that takes two integers and returns their sum?
✗ Incorrect
Rust requires parameter types and return type with
->.What is the return type of a function that does not return any value?
✗ Incorrect
Rust uses the unit type
() for functions with no return value.Explain how to declare a function in Rust that takes parameters and returns a value.
Think about the function signature and how Rust specifies types.
You got /5 concepts.
Describe how Rust handles returning values from functions without using the return keyword.
Remember how Rust treats the last line inside the function.
You got /4 concepts.
