the following piece of code works when validate_with is passed a closure, but fails to compile when I declare a function outside and use it instead
let mail: String = Input::new()
.with_prompt("Enter email")
.validate_with(|input: &String| -> Result<(), &str> {
if input.contains('@') {
Ok(())
} else {
Err("This is not a mail address")
}
})
.interact()
.unwrap();
This fails to compile
fn validator_fn(input: &String) -> Result<(), &str> {
if input.contains('@') {
Ok(())
} else {
Err("This is not a mail address")
}
}
fn main() {
let mail: String = Input::new()
.with_prompt("Enter email")
.validate_with(validator_fn)
.interact()
.unwrap();
}
I get the following error -
mismatched types
expected enum Result<_, &_>
found enum Result<_, &_>
I am fairly new to rust and would like to know where I am going wrong. Thank you for taking time to help.
Lifetime elision is biting you here, because it believes the error string you are returning lives only as long as the reference you pass as an argument to your function and not for 'static. Making this explicit works:
fn validator_fn(input: &String) -> Result<(), &'static str> {
if input.contains('@') {
Ok(())
} else {
Err("This is not a mail address")
}
}
(checking whether a string contains the character '@' is not good enough for validating whether the string is an email address or not)