I am learning Rust and I am writing a unit test using mockall library.
I have some String in my test and I want to pass it to multiple mock closures.
If I pass it directly, then I understand that I would move the ownership to the closure.
So instead I am converting it to &str, but then I get “borrowed value does not live long enough” and “argument requires that is borrowed for `’static”.
I can’t uderstand why the compiler can’t figure out that the String lives long enough as &str in this case. I can make it work using Rc, but I would like to know if there is easier way to fix this.
Here is the mockall return_once signature
use mockall::mock;
pub struct Setting {
pub key: String,
}
impl Clone for Setting {
fn clone(&self) -> Self {
Setting {
key: self.key.clone(),
}
}
}
pub trait TSettingRepository {
fn get(&self, id: &str) -> Setting;
}
mock! {
pub SettingRepository{}
impl TSettingRepository for SettingRepository {
fn get(&self, id: &str) -> Setting {
todo!()
}
}
}
fn main() {
let key_str: String = "some String from external function".to_string();
let key: &str = &key_str; //<- borrowed value does not live long enough
let mut setting_repository = MockSettingRepository::new();
setting_repository.expect_get().return_once(|_| Setting {
key: key.to_string(),
});
setting_repository.expect_get().return_once(|_| Setting {
key: key.to_string(),
});
}