I have a type like this:
#[derive(PartialEq, Eq, Debug, Clone)]
enum MyEnum {
ValueOne,
ValueTwo,
Integer(i32),
Text(String),
}
In my code I have a lot of similar patterns:
let value = match iterator.next() {
Some(MyEnum::ValueOne) => MyEnum::ValueOne,
Some(value) => return Err(format!("Unexpected value {:?}", value)),
None => return Err("Unexpected end of input!"),
}
Or this:
let value = match iterator.next() {
Some(MyEnum::Integer(i)) => MyEnum::Integer(i),
Some(value) => return Err(format!("Unexpected value {:?}", value)),
None => return Err("Unexpected end of input!"),
}
I would like to create a generic function take_value
, where I can specify the MyEnum
type I need, and it returns the Result
I can only solve it with simple values like this:
fn take_value(iterator: &mut Iterator<MyEnum>, expected: MyEnum) -> Result<MyEnum, String> {
match iterator.next() {
Some(expected) => Ok(expected),
Some(value) => Err(format!("Unexpected value {:?}", value)),
None => Err("Unexpected end of input!"),
}
}
It can be called like this: let value = take_value(iterator, MyEnum::ValueOne)?;
But how is it possible to modify this function, so it can be called for MyEnum::Integer, without specifying the integer value inside? Like take_value(iterator, MyEnum::Integer)
CodePudding user response:
You can't do it with a function, but the macro below comes close to what you want.
Because we have to differentiate between patterns :pat
and expressions :expr
you have to repeat that part.
#[derive(PartialEq, Eq, Debug, Clone)]
enum MyEnum {
ValueOne,
ValueTwo,
Integer(i32),
Text(String),
}
macro_rules! take_value {
($iterator:expr, $pattern:pat, $expr:expr) => {
match $iterator.next() {
Some($pattern) => Ok($expr),
Some(value) => Err(format!("Unexpected value {:?}", value)),
None => Err("Unexpected end of input!".to_string()),
}
}
}
fn main() {
let mut it = [MyEnum::ValueOne, MyEnum::ValueTwo, MyEnum::Integer(5)].into_iter();
dbg!(take_value!(&mut it, MyEnum::ValueOne, MyEnum::ValueOne));
dbg!(take_value!(&mut it, MyEnum::ValueOne, MyEnum::ValueOne));
dbg!(take_value!(&mut it, MyEnum::Integer(i), MyEnum::Integer(i)));
dbg!(take_value!(&mut it, MyEnum::ValueOne, MyEnum::ValueOne));
}
…
src/main.rs:21] take_value!(& mut it, MyEnum :: ValueOne, MyEnum :: ValueOne) = Ok(
ValueOne,
)
[src/main.rs:22] take_value!(& mut it, MyEnum :: ValueOne, MyEnum :: ValueOne) = Err(
"Unexpected value ValueTwo",
)
[src/main.rs:23] take_value!(& mut it, MyEnum :: Integer(i), MyEnum :: Integer(i)) = Ok(
Integer(
5,
),
)
[src/main.rs:24] take_value!(& mut it, MyEnum :: ValueOne, MyEnum :: ValueOne) = Err(
"Unexpected end of input!",
)
CodePudding user response:
You can't do it with this kind of "example value". You will need to pass a predicate callback to your take_value
function:
fn take_value<F: Fn(&MyEnum) -> bool>(iterator: &mut dyn Iterator<Item = MyEnum>, predicate: F) -> Result<MyEnum, String> {
match iterator.next() {
Some(value) if predicate (&value) => Ok(value),
Some(value) => Err(format!("Unexpected value {:?}", value)),
None => Err("Unexpected end of input!".to_string()),
}
}
which you then call like:
let value1 = take_value (&mut it, |v| v == &MyEnum::ValueOne);
let integer = take_value (&mut it, |v| matches!(v, MyEnum::Integer (_)));
Optionally, you can hide the fact that the predicate is a callback with a simple macro:
macro_rules! mk_pred {
($pat:pat) => {
|v| matches!(v, $pat)
}
}
which allows calling take_value
like this:
let value1 = take_value (&mut it, mk_pred!(MyEnum::ValueOne));
let integer = take_value (&mut it, mk_pred!(MyEnum::Integer (_)));
CodePudding user response:
An approach that I see a lot in the wild, even if it has some boilerplate, is to simply create one conversion function per enum variant. For example:
impl MyEnum {
pub fn as_value_one(&self) -> Result<(), Error> {
match self {
MyEnum::ValueOne => Ok(()),
_ => Err(self.unexpected_value()),
}
}
pub fn as_integer(&self) -> Result<i32, Error> {
match self {
MyEnum::Integer(i) => Ok(*i),
_ => Err(self.unexpected_value()),
}
}
fn unexpected_value(&self) -> Error {
format!("Unexpected value {:?}", self)
}
}
Usage:
let value = iterator.next()
.ok_or_else(|| "Unexpected end of input!".to_owned())?
.as_value_one()?;
let value: i32 = iterator.next()
.ok_or_else(|| "Unexpected end of input!".to_owned())?
.as_integer()?;
I left the Option
outside of the implementation because it didn't seem to belong here, but you can do it however you like.