pub trait MaybeFrom<T> {
// Required method
fn maybe_from(value: T) -> Option<Self>
where Self: Sized;
}Expand description
A trait for attempting to convert from one type to another.
Similar to the standard library’s From trait, but returns an Option
to indicate whether the conversion was successful.
§Examples
use cutoff_common::MaybeFrom;
// Define a wrapper type for the example
#[derive(Debug, PartialEq)]
struct MyWrapper(String);
// Implementing MaybeFrom for our wrapper type
impl MaybeFrom<i32> for MyWrapper {
fn maybe_from(value: i32) -> Option<Self> {
if value > 0 {
Some(MyWrapper(value.to_string()))
} else {
None
}
}
}
// Using the implementation
let result = MyWrapper::maybe_from(42);
assert_eq!(result.unwrap().0, "42");
let result = MyWrapper::maybe_from(0);
assert_eq!(result, None);