// Make the test compile and pass successfully.
#[cfg(test)]
mod tests {
#[test]
fn you_can_assert_eq() {
assert_eq!();
}
}
Solution
#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
#[test]
fn you_can_assert_eq() {
assert_eq!(7+2, 9); // can use any two expressions that are equal
}
}
}
// Complete the test function's signature.
fn calculate_sum(nums: &[i32]) -> Result<i32, String> {
if nums.len() == 0 {
return Err("Number list is empty".to_string());
}
let mut sum = 0;
for num in nums {
sum += num;
}
Ok(sum)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calculates_sum_correctly() -> {
let nums = [1, 2, 3, 4, 5];
let sum = calculate_sum(&nums)?;
assert_eq!(sum, 5 * (5 + 1) / 2);
Ok(())
}
}
Solution
#![allow(unused)]
fn main() {
fn calculate_sum(nums: &[i32]) -> Result<i32, String> {
if nums.len() == 0 {
return Err("Number list is empty".to_string());
}
let mut sum = 0;
for num in nums {
sum += num;
}
Ok(sum)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn calculates_sum_correctly() -> Result<(), String> {
let nums = [1, 2, 3, 4, 5];
let sum = calculate_sum(&nums)?;
assert_eq!(sum, 5 * (5 + 1) / 2);
Ok(())
}
}
}
// Add a macro to make the test pass.
fn average(nums: &[i32]) -> i32 {
if nums.len() == 0 {
panic!("Empty number list");
}
let mut sum = 0;
for num in nums {
sum += num;
}
sum / nums.len() as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_panics() {
let nums = [];
let _avg = average(&nums);
}
}
Solution
#![allow(unused)]
fn main() {
fn average(nums: &[i32]) -> i32 {
if nums.len() == 0 {
panic!("Empty number list");
}
let mut sum = 0;
for num in nums {
sum += num;
}
sum / nums.len() as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn it_panics() {
let nums = [];
let _avg = average(&nums);
}
}
}