【发布时间】:2022-10-09 17:14:54
【问题描述】:
所以,我写了一个程序来交换 rust 中的两个数字,我把下面的代码和它的测试函数一起粘贴了。当我运行 cargo run 时,我的 swap() 和 main() 方法可以正常工作并正确交换程序中的值,但是当我运行 cargo test 时它不会编译,而且我不确定如何更正我的测试函数。谁能告诉我我的函数中缺少什么,或者我是否完全写错了?谢谢!
fn swap(a: &mut u32, b: &mut u32) {
let temp: u32 = *a; // stores value of a in temp
*a = *b; // assigns the value of b to a
*b = temp; // assigns the value of temp (which is a) to b
// values are now swapped
}
fn main() {
let mut a = 26; // assigns value 26.0 to a
let mut b = 10; // assigns value 10.0 to b
println!{"Before swap: "};
println!("{}, {}", a, b); // prints orginal values for a and b
swap(&mut a, &mut b); // calls swap funciton
println!("After swap: ");
println!("{}, {}", a, b); // prints the swapped values for a and b (expecting "10, 26")
}
#[test]
fn test_swap() {
assert!(swap(&mut 26, &mut 10) == 10u32, 26u32);
}
【问题讨论】:
-
swap不返回任何内容。你不能将它的返回值与任何东西(但(),我猜)进行比较,因为没有。