我有一个涉及宏的编译错误:
<mdo macros>:6:19: 6:50 error: cannot move out of captured outer variable in an `FnMut` closure
<mdo macros>:6 bind ( $ e , move | $ p | mdo ! { $ ( $ t ) * } ) ) ; (
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
<mdo macros>:6:27: 6:50 note: expansion site
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
<mdo macros>:6:27: 6:50 note: expansion site
<mdo macros>:1:1: 14:36 note: in expansion of mdo!
src/parser.rs:30:42: …Run Code Online (Sandbox Code Playgroud) 我想申请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)
有冗长模式匹配的替代方案吗?我寻找一个宏但找不到合适的宏.
编者注:此代码示例来自1.0之前的Rust版本,并且在语法上不是有效的Rust 1.0代码.此代码的更新版本会产生不同的错误,但答案仍包含有价值的信息.
在下列情况下,似乎我们无法测试相等性.为什么是这样?有解决方法吗?(我正在使用Rust 0.11).
trait A: PartialEq {}
#[deriving(PartialEq)]
enum T {Ta, Tb}
impl A for T {}
fn main() {
assert!(Ta == Ta);
assert!(Ta != Tb);
assert!(some_fn(&Ta, &Ta));
assert!(!some_fn(&Ta, &Tb));
}
fn some_fn(an_a: &A, another_a: &A) -> bool {
an_a == another_a
// ERROR ^~~~~~~~~~~~ binary operation `==` cannot be applied to type `&A`
}
fn another_fn(an_a: &A + PartialEq, another_a: &A + PartialEq) -> bool {
// ERROR: ^~~~~~~~~ only the builtin traits can be used as closure …Run Code Online (Sandbox Code Playgroud) 我想在一个中使用特征对象Vec.在C++中我可以使一个基类Thing从中导出Monster1和Monster2.然后我可以创建一个std::vector<Thing*>.Thing对象必须存储一些数据,例如x : int, y : int,派生类需要添加更多数据.
目前我有类似的东西
struct Level {
// some stuff here
pub things: Vec<Box<ThingTrait + 'static>>,
}
struct ThingRecord {
x: i32,
y: i32,
}
struct Monster1 {
thing_record: ThingRecord,
num_arrows: i32,
}
struct Monster2 {
thing_record: ThingRecord,
num_fireballs: i32,
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个ThingTrait与方法get_thing_record(),attack(),make_noise()等,并实现它们的Monster1和Monster2.
我正在尝试检查两个(功能相同)结构的相等性.
#[derive(PartialEq, Debug)]
pub struct TypeA<'a>(&'a str);
#[derive(PartialEq, Debug)]
pub struct TypeB<'a>(&'a str);
impl<'a> TypeA<'a> {
pub fn new(n: &str) -> TypeA {
TypeA(n)
}
}
impl<'a> TypeB<'a> {
pub fn new(n: &str) -> TypeB {
TypeB(n)
}
}
fn main() {
assert_eq!(TypeA::new("A"), TypeB::new("A"));
}
Run Code Online (Sandbox Code Playgroud)
它返回错误:
error[E0308]: mismatched types
--> src/main.rs:20:5
|
20 | assert_eq!(TypeA::new("A"), TypeB::new("A"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `TypeA`, found struct `TypeB`
|
= note: expected type `TypeA<'_>`
found type `TypeB<'_>`
= note: this error originates in a …Run Code Online (Sandbox Code Playgroud)