问题描述
我有一个函数,它接受一个数字作为参数,然后根据这个数字返回一个函数.根据许多不同的事情,它可能会返回大约 50 个函数中的任何一个,并且它应该返回的情况变得非常复杂.因此,我想构建一些测试以确保返回正确的函数.到目前为止,我所拥有的大致如下.
I have a function which takes a number as an argument, and then returns a function based on the number. Depending on many different things, it might return any of ~50 functions, and the cases for which one it should return get pretty complicated. As such, I want to build some tests to make sure the proper functions are being returned. What I have so far looks roughly like this.
fn pick_a_function(decider: u32) -> fn(&mut SomeStruct) {
match decider {
1 => add,
2 => sub,
_ => zero,
}
}
fn add(x: &mut SomeStruct) {
x.a += x.b;
}
fn sub(x: &mut SomeStruct) {
x.a -= x.b;
}
fn zero(_x: &mut SomeStruct) {
x.a = 0;
}
fn main() {
let mut x = SomeStruct { a: 2, b: 3 };
pick_a_function(1)(&mut x);
println!("2 + 3 = {}", x.a);
}
#[cfg(test)]
mod tests {
use super::*;
fn picks_correct_function() {
assert_eq!(pick_a_function(1), add);
}
}
问题是这些函数似乎没有实现 Eq
或 PartialEq
特性,所以 assert_eq!
只是说它可以不要比较它们.我有哪些选项可以将返回的函数与正确的函数进行比较?
The problem is that the functions don't seem to implement the Eq
or PartialEq
traits, so assert_eq!
just says that it can't compare them. What options do I have for comparing the returned function to the correct function?
推荐答案
你应该比较结果而不是函数,例如:
You should compare the result instead of the function,for example:
#[cfg(test)]
mod tests {
use super::*;
fn picks_correct_function() {
let add_picked = pick_a_function(1);
assert_eq!(add_picked(1,2), add(1,2));
}
}
或者在更复杂的场景中,您可以比较函数的输入,该函数采用一个参数,另一个采用两个参数,尝试调用其中任何一个,看看是否出现编译器错误.
Or in more complex scenarios you can compare the inputs making a function that takes one parameter and another that takes two,try to call any of them and see if you get a compiler error.
这篇关于在 Rust 中比较函数的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!