I commonly write tests in other languages where I explicitly define expected and actual values. In Rust, I was running into lifetime errors because my test code creates a struct that uses a value from another struct.
Two ways I have found to avoid this is to: a) use references with the struct type defined with a pointer or b) use cloning. I have seen may posts asking how to avoid excessive cloning so I am simply wondering is there a more idiomatic way of doing this?
Can I get rid of the use of clone
in the following test:
#[derive(Clone, Debug, PartialEq)]
struct SomethingElse {
a: u16,
}
struct Something {
inner: SomethingElse,
}
impl Something {
pub fn do_something(&self) -> SomethingElse {
return self.inner.clone();
}
}
mod tests {
#[cfg(test)]
use super::*;
#[test]
fn something_does_something() {
let expected = SomethingElse { a: 1 };
let something = Something {
inner: expected.clone(),
};
assert_eq!(something.do_something(), expected);
}
}
Aucun commentaire:
Enregistrer un commentaire