Complete the code to return the sum of two numbers.
fn add(a: i32, b: i32) -> i32 {
[1]
}The function should return the sum of a and b. Using a + b returns the correct value.
Complete the code to return the length of the string slice.
fn length(s: &str) -> usize {
[1]
}s.len(), which makes the function return ().length() or size().In Rust, len() returns the length of a string slice. The last expression without a semicolon is returned.
Fix the error in the function to correctly return the boolean result.
fn is_even(num: i32) -> bool {
if num % 2 == 0 {
[1]
} else {
false
}
}true, which causes the function to return ().return true; inside the if block but missing return in else.In Rust, the last expression without a semicolon is returned. Using true without a semicolon returns the value correctly.
Fill both blanks to return a tuple with the sum and product of two numbers.
fn sum_and_product(a: i32, b: i32) -> (i32, i32) {
let sum = a [1] b;
let product = a [2] b;
(sum, product)
}The sum is calculated with + and the product with *.
Fill all three blanks to return a HashMap with words as keys and their lengths as values, only for words longer than 3 characters.
use std::collections::HashMap;
fn word_lengths(words: Vec<&str>) -> HashMap<String, usize> {
let mut lengths = HashMap::new();
for word in words {
if word.[1]() > 3 {
lengths.insert(word.[2](), word.[3]());
}
}
lengths
}chars() instead of len() for length.We check the length with len(), convert the word to a String with to_string(), and get the length again with len() for the value.
