Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Checking whether the String contains a Character Other than the Specific Characters
I have the following code:
#[derive(Eq, PartialEq, PartialOrd, Ord, Clone, Hash, Debug)]
pub struct Id(String);
impl TryFrom<&str> for Id {
type Error = Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let mut value_i = value.chars();
if match value_i.next() {
Some(some) => match some {
'_' | 'A'..='Z' | 'a'..='z' => true,
'0'..='9' | _ => false,
},
None => return Err(Error::EmptyId),
} {
value_i.next();
while let Some(c) = value_i.next() {
match c {
'_' | '0'..='9' | 'A'..='Z' | 'a'..='z' => continue,
_ => return Err(Error::BadId(String::from(value))),
}
}
}
Ok(Id(String::from(value)))
}
}
And this code looks horrible to me.
It does work correctly, but I feel like there is a better way to achieve what the function does. I would like to also ask about naming. Should I rename the structure type Id to Ident or Identifier, or is it fine?
If what the function does is not clear, it reads the given string value and returns an error if it contains a character other than '_' | '0'..='9' | 'A'..='Z' | 'a'..='z'
, and it also checks whether the string starts with a number.
24 posts - 7 participants
🏷️ rust_feed