【问题标题】:How to match enum with parameter without destructing in Rust?如何在不破坏 Rust 的情况下将枚举与参数匹配?
【发布时间】:2021-01-01 17:45:57
【问题描述】:

我有带有值变量的枚举:

enum Foobar<T, G> {
    Foo,
    Bar(T),
    Baz(G),
}

我有一段代码需要匹配枚举值,但我不想破坏它。

fn foobar<T, G, F1, F2>(value: Foobar<T, G>, f1: F1, f2: F2) -> bool
where
    F1: Fn(T) -> bool,
    F2: Fn(G),
{
    let res = match value {
        Foobar::Foo => true,
        Foobar::Bar(v) => f1(v),
        Foobar::Baz => false,
    };
    if let Foobar::Baz(v2) = value {
        f2(v2);
    }
    res
}

它不会编译,因为expected unit struct, unit variant or constant, found tuple variant Foobar::Baz

我不想将其更改为 Foobar::Baz(_),因为它会强制 G 上的 Copy trait,我不想要它。

我的例子有点人为,但假设我需要单独调用f2

有没有办法匹配枚举变体而不破坏它?

【问题讨论】:

    标签: rust pattern-matching move-semantics


    【解决方案1】:

    你不能。

    但无论如何也无济于事。问题是valuematch 之后不可用,因为您(可能已经)将数据从它移到了f1

    您可以通过稍微重新组织代码来修复它,以便您只在 Bar 的值没有移动时查看 Baz

    fn foobar<T, G, F1, F2>(value: Foobar<T, G>, f1: F1, f2: F2) -> bool
    where
        F1: Fn(T) -> bool,
        F2: Fn(G),
    {
        let res = match value {
            Foobar::Foo => true,
            Foobar::Bar(v) => f1(v),
            Foobar::Baz(v2) => {
                f2(v2);
                false
            },
        };
        res
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 2015-03-17
      • 1970-01-01
      相关资源
      最近更新 更多