【发布时间】:2015-11-20 11:39:33
【问题描述】:
我有这个闭包类型别名:
type ClosureType = Box<Fn(i32) -> i32>;
这个特性:
trait Trait {
fn change(&self, y: i32) -> i32;
}
还有这些功能:
fn with_one(x: Box<Fn(i32) -> i32>) -> i32 {
x(1)
}
fn plus_one(x: i32) -> i32 {
x+1
}
fn main() {
let a = Box::new(|x: i32|{x+1});
let b: ClosureType = Box::new(|x: i32|{x+1});
let c = Box::new(plus_one);
let d: ClosureType = Box::new(plus_one);
println!("{}", a.change(1));
println!("{}", b.change(1));
println!("{}", c.change(1));
println!("{}", d.change(1));
println!("{}", with_one(a));
println!("{}", with_one(b));
println!("{}", with_one(c));
println!("{}", with_one(d));
}
当我为ClosureType 或Box<Fn(i32) -> i32> 实现特征Trait 时,如果我正确理解类型别名,则相同:
impl Trait for ClosureType {
fn change(&self, y: i32) -> i32{
self(y)
}
}
或
impl Trait for Box<Fn(i32) -> i32> {
fn change(&self, y: i32) -> i32{
self(y)
}
}
对于变量a 我得到:
<anon>:32:22: 32:31 error: no method named `change` found for type
`Box<[closure <anon>:28:22: 28:35]>` in the current scope
<anon>:32 println!("{}", a.change(1));
对于变量c 我得到:
<anon>:34:22: 34:31 error: no method named `change` found for type
`Box<fn(i32) -> i32 {plus_one}>` in the current scope
<anon>:34 println!("{}", c.change(1));
然而变量 a 和 c 被函数 with_one(x: Box<Fn(i32) -> i32>) -> i32 接受,换句话说,它们似乎对于函数 with_one 具有相同的类型(Box<Fn(i32) -> i32>)但不同(Box<[closure <anon>:24:22: 24:35]> 和 @987654340 @) 用于 Trait 实现。
我觉得我在这里遗漏了一些东西,但不确定是什么,你能告诉我吗?
你可以在this rust playground找到所有代码。
【问题讨论】:
标签: closures rust traits type-alias