问题描述
有没有办法在不使用 &Box<T>
的情况下对 as_ref
进行模式匹配?我使用的是稳定的 Rust,所以答案不能涉及 Box_patterns
。
enum Foo {
Thing(Box<ThingKind>),}
enum ThingKind {
One(Foo),Two(Foo,Foo),}
fn my_function(foo: &Foo) {
match foo {
Foo::Thing(ThingKind::One(_inner)) => { /* ... */ }
Foo::Thing(ThingKind::Two(_left,_right)) => { /* ... */ }
}
}
但编译器不喜欢那样:
error[E0308]: mismatched types
--> src/lib.rs:12:20
|
11 | match foo {
| --- this expression has type `&Foo`
12 | Foo::Thing(ThingKind::One(_inner)) => { /* ... */ }
| ^^^^^^^^^^^^^^^^^^^^^^ expected struct `Box`,found enum `ThingKind`
|
= note: expected struct `Box<ThingKind>`
found enum `ThingKind`
error[E0308]: mismatched types
--> src/lib.rs:13:20
|
11 | match foo {
| --- this expression has type `&Foo`
12 | Foo::Thing(ThingKind::One(_inner)) => { /* ... */ }
13 | Foo::Thing(ThingKind::Two(_left,_right)) => { /* ... */ }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Box`,found enum `ThingKind`
|
= note: expected struct `Box<ThingKind>`
found enum `ThingKind`
error: aborting due to 2 prevIoUs errors
然后我尝试了这个:
enum Foo {
Thing(Box<ThingKind>),}
fn my_function(foo: &Foo) {
match foo {
Foo::Thing(kind) => match kind {
ThingKind::One(_inner) => { /* ... */ }
ThingKind::Two(_left,_right) => { /* ... */ }
},}
}
但是编译器也给出了类似的错误。
然后我尝试在内部 kind.as_ref()
中使用 match
,确实有效,但是每次都必须添加它有点烦人。那么,有没有没有 as_ref
的方法呢?
解决方法
这看起来像是 std::ops::Deref
的工作。
JSON.parse(event.body)