I am new to rust and started to write some code a couple of days ago.
Question:
Lets say i have this function:
fn get_text() -> Result<String> {
let texts = vec!["Hello"];
return match texts.len() {
0 => Err("text not found"),
1 => texts.first().cloned().ok_or("text can not be none"),
_ => Err("Too many texts found")
}
in the match where I check for 1, I need to .ok_or() the Option and handle the None case. Is there a way to simply ignore None? Or a better way in general?
Because the check for texts.len() == 1 already asserts that the vector has at least one element. Its kinda redundant to also have to check for None, because its impossible that first() returns None.
I moved texts to a parameter (and Strings instead of &strs) to demonstrate that this doesn't need to copy anything -- it moves the one element of the vector into the array pattern.
Actually, the error type there gives another way to write it that avoids the pre-check:
pub fn get_text(texts: Vec<String>) -> Result<String, String> {
let [text]: [_; 1] = texts.try_into().map_err(|v: Vec<String>| {
if v.is_empty() {
"text not found"
} else {
"Too many texts found"
}
})?;
Ok(text)
}