为什么在从一个泛型映射到另一个泛型时必须破坏和重建泛型枚举的非泛型变体?

Why do I have to destruct and reconstruct the non-generic variant of a generic enum when mapping from one generic to another?

我有一个通用枚举,其中只有一个变体使用通用类型。

当将 ParseResult<T>“转换”为 ParseResult<U> 时,编译器也强制我销毁非泛型部分。非通用部分立即重新组装并以完全相同的方式返回。

没有代码重复的更优雅的解决方案吗?

#[derive(PartialEq, Debug)]
enum ParseResult<'a, T> {
    Success(T, &'a str),
    Failure(&'static str),
}

fn char<'a>(c: char) -> impl Fn(&'a str) -> ParseResult<'a, char> {
    move |input| match input.chars().next() {
        Some(candidate) if c == candidate => ParseResult::Success(candidate, &input[1..]),
        Some(_) => ParseResult::Failure("chars didn't match"),
        None => ParseResult::Failure("unexpected end of stream"),
    }
}

fn or<'a, T>(
    mut lhs: impl FnMut(&'a str) -> ParseResult<T>,
    mut rhs: impl FnMut(&'a str) -> ParseResult<T>,
) -> impl FnMut(&'a str) -> ParseResult<T> {
    move |input| match lhs(input) {
        ParseResult::Failure(_) => rhs(input),
        ok => ok,
    }
}

fn and<'a, T, U>(
    mut lhs: impl FnMut(&'a str) -> ParseResult<T>,
    mut rhs: impl FnMut(&'a str) -> ParseResult<U>,
) -> impl FnMut(&'a str) -> ParseResult<(T, U)> {
    move |input| match lhs(input) {
        ParseResult::Success(left, after) => match rhs(after) {
            ParseResult::Success(right, after) => ParseResult::Success((left, right), after),
            // Only explicit works:
            ParseResult::Failure(why) => ParseResult::Failure(why),
        },
        // Same as line as above, same goes here.
        ParseResult::Failure(why) => ParseResult::Failure(why),
    }
}

结尾处的两条 ::Failure 行无效的地方:

  1. bad => bad, 预期元组,找到类型参数 U
  2. bad => bad as ParseResult<(T, U)>,
  3. bad @ ParseResult::Failure(why) => bad, 预期元组,找到类型参数 U

Playground

But the non-generic part is immediately reassembled and returned in exactly the same way. Isn't there a smarter/more elegant solution without the code duplication?

看起来它是以相同的方式重新组装的,但这不是因为它将类型从 ParseResult<T> 更改为 ParseResult<U>(或在您的情况下为 ParseResult<(T, U)>)。它们具有不同的大小,因此 ParseResult<T>::Failed(err)ParseResult<U>::Failed(err) 不同。

如果我们查看 how the standard library handles this problem for Result::map,您会发现使用了相同的模式:

match self {
     Ok(t) => Ok(op(t)),
     Err(e) => Err(e),
}