// Complete the function to make the program execute successfully.
fn append(nums, num) {
}
fn main() {
let mut nums = vec![1, 2, 5, 6];
append(&mut nums, 8);
append(&mut nums, 3);
assert_eq!(nums.len(), 6);
}
// Complete the function to make the program execute successfully.
fn remove_if_odd(nums, index) {
if index > nums.len() {
println!("Index out of bounds");
return;
}
}
fn main() {
let mut nums = vec![1, 2, 6, 9];
let nums_ref = &mut nums;
remove_if_odd(nums_ref, 0);
remove_if_odd(nums_ref, 1);
remove_if_odd(nums_ref, nums_ref.len() - 1);
assert_eq!(nums.len(), 2);
}
Solution
fn remove_if_odd(nums: &mut Vec<i32>, index: usize) {
if index > nums.len() {
println!("Index out of bounds");
return;
}
if nums[index] % 2 == 1 {
nums.remove(index);
}
}
fn main() {
let mut nums = vec![1, 2, 6, 9];
let nums_ref = &mut nums;
remove_if_odd(nums_ref, 0);
remove_if_odd(nums_ref, 1);
remove_if_odd(nums_ref, nums_ref.len() - 1);
assert_eq!(nums.len(), 2);
}
// Fix the code so that it compiles.
fn main() {
let names = vec!["Alice", "Bob", "Cindy"];
let index = 2;
if names.get(index) {
println!("{name} is present at index {index}");
} else {
println!("invalid index {index}");
}
}
Solution
fn main() {
let names = vec!["Alice", "Bob", "Cindy"];
let index = 2;
if let Some(name) = names.get(index) {
println!("{name} is present at index {index}");
} else {
println!("invalid index {index}");
}
}