Types fn在trait中使用FnMut闭包->;或;模式不是';“不允许在没有实体的函数中使用”;或;请加上mut“; pub结构A{} 酒馆{ fn-foo(&self,mut-fnmuti32:VF) 哪里 VF:FnMut(i32); } 为一个{ fn-foo(&self,mut-fnmuti32:VF) 哪里 VF:FnMut(i32), { 对于1..5中的x{ fn32(x); } } } #[cfg(测试)] 模试验{ 使用超级::*; #[测试] fn测试_00(){ 设a=a; 让mut v=Vec::new(); 设bar=|x{v.push(x);}; a、 富(巴);; 断言(v,vec![1,2,3,4]); } }
编译器抱怨:Types fn在trait中使用FnMut闭包->;或;模式不是';“不允许在没有实体的函数中使用”;或;请加上mut“; pub结构A{} 酒馆{ fn-foo(&self,mut-fnmuti32:VF) 哪里 VF:FnMut(i32); } 为一个{ fn-foo(&self,mut-fnmuti32:VF) 哪里 VF:FnMut(i32), { 对于1..5中的x{ fn32(x); } } } #[cfg(测试)] 模试验{ 使用超级::*; #[测试] fn测试_00(){ 设a=a; 让mut v=Vec::new(); 设bar=|x{v.push(x);}; a、 富(巴);; 断言(v,vec![1,2,3,4]); } },types,rust,closures,Types,Rust,Closures,编译器抱怨: error: patterns aren't allowed in functions without bodies --> src/lib.rs:9:23 | 9 | fn foo<VF>(&self, mut fnmuti32: VF) | ^^^^^^^^^^^^ help: remove `mut` from the parameter: `fnmuti32` <--cut--&g
error: patterns aren't allowed in functions without bodies
--> src/lib.rs:9:23
|
9 | fn foo<VF>(&self, mut fnmuti32: VF)
| ^^^^^^^^^^^^ help: remove `mut` from the parameter: `fnmuti32`
<--cut-->
问题是您在特征定义中指定了
mut
。mut
使变量绑定可变,这种信息属于trait实现,而不是声明
如果删除特征定义上的
mut
,代码将编译。代码中有一些错误,这应该可以正常工作:
pub结构A;
酒馆{
fn foo(&self,Fnmut32:VF)
哪里
VF:FnMut(i32);
}
为一个{
fn-foo(&self,mut-fnmuti32:VF)
哪里
VF:FnMut(i32),
{
对于1中的x..=5{
fn32(x);
}
}
}
#[cfg(测试)]
#[允许(未使用的_导入)]
模试验{
使用超级::*;
#[测试]
fn测试_00(){
设a=a;
让mut v=Vec::new();
设bar=|x{v.push(x);};
a、 富(巴);;
断言(v,vec![1,2,3,4,5]);
}
}
struct A{}
替换为struct A
以便A
可以用作A
的唯一实例值,而不是A{}
mut
关键字只是实现的问题,因为只要所有权转移到函数中,调用方就不再决定实现是否会改变参数。
1..5
更改为1..=5
,以便结果与提供的测试用例匹配
这回答了你的问题吗?一点也不,因为在我的例子中,
trait
和实现impl
之间的语义差异问题。在他的第2点中准确地抓住了问题,这就是为什么我编辑了他的答案,突出了第2点。请为你们的第1点提供引证struct A{}
和struct A
都是零大小的。@Shepmaster我不是说struct A{}
不是零大小的。但是有一些方法可以定义ZST。当值用a
实例化时,定义必须是struct a代码>以便它可以编译。
Compiling playground v0.0.1 (/playground)
error[E0596]: cannot borrow `fnmuti32` as mutable, as it is not declared as mutable
--> src/lib.rs:20:13
|
15 | fn foo<VF>(&self, fnmuti32: VF)
| -------- help: consider changing this to be mutable: `mut fnmuti32`
...
20 | fnmuti32(x);
| ^^^^^^^^ cannot borrow as mutable
<--cut-->