|
|
|
|
|
by tialaramex
1205 days ago
|
|
And parse-don't-validate is often very nice to work with in Rust, I can describe how to turn some UTF-8 text into my type Foo in a function: impl std::str::FromStr for Foo {
type Err = ReasonsItIsNotAFoo;
fn from_str(s: &str) -> Result<Self, Self::Err> {
/* etc. */
}
}
And then whenever I've got a string which I know ought to be a Foo, I can: let foo: Foo = string.parse().expect("This {string:?} ought to be a Foo but it isn't");
Since we said foo is a Foo, by inference the parsing of string needs to either succeed with a Foo, or fail while trying, so it calls that FromStr implementation we wrote earlier to achieve that. |
|