Rust Fundamentals · 15 XP
Expressions and blocks
Rust distinguishes statements (they do something and produce no value) from
expressions (they evaluate to a value). Almost everything is an expression,
including blocks and if.
A block { ... } evaluates to its last expression, as long as that line has
no trailing semicolon:
let area = {
let side = 4;
side * side
}; // area is 16
if is an expression too, so it can produce a value. Both branches must have
the same type:
let label = if area > 10 { "big" } else { "small" };
Adding a ; after the last line of a block turns it into a statement, and the
block then evaluates to () (the empty "unit" value). That is the most common
cause of a "mismatched types" error when you try to return a value.
Your task
Write these three public functions. Do not use the return keyword in any of
them. (&'static str is the type of text written directly in your code, like
"zero"; the course explains the & and 'static parts later.)
sign_word(n: i32) -> &'static strreturns"negative","zero"or"positive", using anif / else if / elsechain as the last expression.max_of_two(a: i32, b: i32) -> i32returns the larger number, withifas an expression.shifted_double(x: i32) -> i32uses a block to add3tox, then doubles the result. For exampleshifted_double(2)is10.