相关疑难解决方法(0)

如何在没有模式匹配的情况下比较枚举

我想申请filter一个迭代器,我想出了这个并且它可以工作,但它超级详细:

.filter(|ref my_struct| match my_struct.my_enum { Unknown => false, _ => true })
Run Code Online (Sandbox Code Playgroud)

我宁愿写这样的东西:

.filter(|ref my_struct| my_struct.my_enum != Unknown)
Run Code Online (Sandbox Code Playgroud)

这给了我一个编译错误

binary operation `!=` cannot be applied to type `MyEnum`
Run Code Online (Sandbox Code Playgroud)

有冗长模式匹配的替代方案吗?我寻找一个宏但找不到合适的宏.

enums pattern-matching rust

30
推荐指数
4
解决办法
2万
查看次数

在Rust中具有常量值的枚举

我可以做这个:

enum MyEnum {
    A(i32),
    B(i32),
}
Run Code Online (Sandbox Code Playgroud)

但不是这个:

enum MyEnum {
    A(123), // 123 is a constant
    B(456), // 456 is a constant
}
Run Code Online (Sandbox Code Playgroud)

我可以创建结构的A和B用单场,然后执行该领域,但我觉得可能是一个更简单的方法.有没有?

rust

28
推荐指数
4
解决办法
2万
查看次数

如何将枚举引用转换为数字?

我有一个枚举:

enum Foo {
    Bar = 1,
}
Run Code Online (Sandbox Code Playgroud)

如何将对此枚举的引用转换为要在数学中使用的整数?

fn f(foo: &Foo) {
    let f = foo as u8;  // error[E0606]: casting `&Foo` as `u8` is invalid
    let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8`
    let f = *foo as u8; // error[E0507]: cannot move out of borrowed content
}
Run Code Online (Sandbox Code Playgroud)

rust

20
推荐指数
1
解决办法
8672
查看次数

如何为枚举实现PartialEq?

我有以下定义:

enum Either<T, U> {
    Left(T),
    Right(U),
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到#[derive(PartialEq)]这种类型的等价物?我想使用一个match表达式,如:

impl<T: PartialEq, U: PartialEq> PartialEq for Either<T, U> {
    fn eq(&self, other: &Either<T, U>) -> bool {
        use Either::*;
        match (*self, *other) {
            (Left(ref a), Left(ref b)) => a == b,
            (Right(ref a), Right(ref b)) => a == b,
            _ => false,
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这既消耗*self和*other,即使我只需要它的match表达,导致错误:

error[E0507]: cannot move out of borrowed content
 --> src/lib.rs:9:16
  |
9 |         match (*self, *other) …
Run Code Online (Sandbox Code Playgroud)

rust

11
推荐指数
1
解决办法
7757
查看次数

如何获取枚举的整数值?

可以编写这样的结构:

enum Number {
    One = 1,
    Two = 2,
    Three = 3,
    Four = 4,
}
Run Code Online (Sandbox Code Playgroud)

但出于什么目的?我找不到任何方法来获取枚举变量的值.

rust

9
推荐指数
1
解决办法
2197
查看次数

如何为Rust中的枚举指定表示类型以与C++接口?

有没有办法在Rust中使用显式表示类型进行C++样式枚举?例:

enum class Number: int16_t {
    Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine
};
Run Code Online (Sandbox Code Playgroud)

如果没有,还有另一种方法可以组织这样的变量吗?我正在与外部库连接,因此指定类型很重要.我知道我可以这样做:

type Number = int16_t;
let One: Number = 1;
let Two: Number = 2;
let Three: Number = 3;
Run Code Online (Sandbox Code Playgroud)

但在我看来,这引入了很多冗余;


注意这个问题不是重复的是否可以在Rust中包装C枚举?因为它是关于包装C++,而不是包装C.

enums rust

5
推荐指数
1
解决办法
801
查看次数

标签 统计

rust ×6

enums ×2

pattern-matching ×1