-
Perhaps this has a more general solution, but I simply need to derive a struct with a boolean field where the input string has form "True" or "False". Here is some test code:
Of course, test #1 fails and test #2 semi-works, but I would prefer to not have to pre-process the incoming string this way (it screws with the other fields). Is there a better way to handle this case? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Create a use parse_display::{Display, DisplayFormat, FromStr, FromStrFormat};
use std::str::FromStr;
#[derive(Display, FromStr)]
#[display("{name}|{flag}")]
struct Test {
name: String,
#[display(with = IgnoreCase)]
flag: bool,
}
struct IgnoreCase;
impl<T: std::fmt::Display> DisplayFormat<T> for IgnoreCase {
fn write(&self, f: &mut std::fmt::Formatter, value: &T) -> std::fmt::Result {
write!(f, "{}", value)
}
}
impl<T: std::str::FromStr> FromStrFormat<T> for IgnoreCase {
type Err = T::Err;
fn parse(&self, s: &str) -> core::result::Result<T, Self::Err> {
s.to_lowercase().parse()
}
}
fn main() {
let s = "Some Name|True";
if let Ok(test) = Test::from_str(s) {
println!("#1. {test}");
}
if let Ok(test) = Test::from_str(&s.to_lowercase()) {
println!("#2. {test}");
}
} Since the use parse_display::{Display, FromStr, FromStrFormat};
use std::str::FromStr;
#[derive(Display, FromStr)]
#[display("{name}|{flag}")]
struct Test {
name: String,
#[from_str(with = IgnoreCase)]
flag: bool,
}
struct IgnoreCase;
impl<T: std::str::FromStr> FromStrFormat<T> for IgnoreCase {
type Err = T::Err;
fn parse(&self, s: &str) -> core::result::Result<T, Self::Err> {
s.to_lowercase().parse()
}
} |
Beta Was this translation helpful? Give feedback.
Create a
FromStrFormat
(IgnoreCase
in the example below) that converts the string to lowercase before parsing, and apply it to theflag
field so that#1
can also be parsed.