How can I print Option<String> such that None prints as None while Some("abc") prints as just "abc" rather than Some("abc"). This is to make the output more readable.
I implemented a workaround that creates a separate variable for the thing I wanna debug. This separate variable takes the original variable and iterates through all its elements and does .unwrap_or("None".to_string()). So the debug output looks good now. But I think this still has the problem of making the code messy. Is there a cleaner way to achieve a clean print output?
fn print_option<T>(x: Option<T>)
where
T: std::fmt::Debug,
{
if let Some(x) = x {
println!("{x:?}");
} else {
println!("None");
}
}
You can add a layer of reference. I'd advise you keep the Some wrapper in your output anyway, since you're using the debug representation of Option. Keep it coherent and simple.
I don't think this is that much cleaner compared to the impl I wrote about. I guess this is something that Rust needs to add intrinsically to the language design. Perhaps of similar nature as {:?} but perhaps some other symbol.
I need the Some wrapper removed because the output will be read by people who aren't familiar with Rust, and they might think that the Some wrapper is part of the value and they might get confused.
Edit: Actually, while this one simplifies Display implementations for many use-cases, it seems like special handling of different enum variants of an existing enum (Option) in a field is not something it can help much with.
Not quite, these would be displayed as "None" and None (note the lack of delimiters) if I'm understanding correctly.
It's still fragile though if used with types other than String. I'm not sure how I'd expect an Option<Option<T>> to be formatted to distinguish between None and Some(None).