Consider the following Rust code. What will be printed when greet("Alice") is called?
fn greet(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
greet("Alice");
}Look at how the println! macro uses curly braces {} to insert the variable.
The function greet takes a string slice &str and prints "Hello, Alice!" by replacing {} with the value of name.
What value does the function add return when called with add(3, 4)?
fn add(x: i32, y: i32) -> i32 {
x + y
}
fn main() {
let result = add(3, 4);
println!("{}", result);
}The function returns the sum of x and y without a semicolon.
In Rust, the last expression without a semicolon is the return value. Here, x + y returns 7.
What error will the Rust compiler report for this function?
fn multiply(x: i32, y: i32) -> i32 {
return x * y;
println!("This line is unreachable");
}
fn main() {
let result = multiply(2, 3);
println!("{}", result);
}Think about what happens after a return statement in Rust.
The println! after return is unreachable code. Rust warns but still compiles.
Choose the correct Rust function declaration that returns a boolean value.
Remember Rust uses -> for return type and bool as the boolean type.
Option D uses correct syntax: return type bool, arrow ->, and comparison operator ==.
What will be printed when factorial(4) is called?
fn factorial(n: u32) -> u32 {
match n {
0 => 1,
_ => n * factorial(n - 1),
}
}
fn main() {
println!("{}", factorial(4));
}Recall factorial of 4 is 4 * 3 * 2 * 1.
The function uses recursion and pattern matching. factorial(4) = 4 * factorial(3) = 24.
