I am struggling with this repeated pattern:
let new_string = if old_string.is_empty() {
"default".to_string()
} else {
old_string
}
For Rust, I believe that there must be a simple way to say this. Could anyone tell me?
I am struggling with this repeated pattern:
let new_string = if old_string.is_empty() {
"default".to_string()
} else {
old_string
}
For Rust, I believe that there must be a simple way to say this. Could anyone tell me?
If you are using empty string as an internal representation of absent field, you should use Option<String>
instead.
If you are dealing with input data, why not just write a function?
If you're doing it all the time, you can make it a macro or method or such.
trait StringExt {
fn or_if_empty(self, dflt: &str) -> String;
}
impl<S: Into<String>> StringExt for S {
fn or_if_empty(self, dflt: &str) -> String {
// Re-use a `String`s capacity, maybe
let mut s = self.into();
if s.is_empty() {
s.push_str(dflt);
}
s
}
}
what are you expecting? empty string is not treated as some kind of special value in rust anyway. and, you can just trivially make a function yourself, as demonstrated by @quinedot
but I think you should consider the advice by @zirconium-n
if in your case, an empty string is not a valid representation for your problem domain, you can just encode it using rust's type system. for instance:
struct NonEmptyString(String);
impl NonEmptyString {
fn new(s: String) -> Option<Self> {
if s.is_empty() {
None
} else {
Some(NonEmptyString(s))
}
}
}
impl Default for NonEmptyString {
fn default() -> Self {
NonEmptyString("default".into())
}
}
in code, if an function only handles sanitized and well-formed input, take a NonEmptyString
as parameter, otherwise, take an Option<NonEmptyString>
.
then your original problem just became
// old_string is Option<NonEmptyString>
// we want an NonEmptyString
let new_string = old_string.unwrap_or_default();
old_string.is_empty().then(|| "default".into()).unwrap_or(old_string);
if you only need &str
:
old_string.is_empty().then_some("default").unwrap_or(&old_string);
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.