我预计以下代码无法编译,但它确实编译了(playground):
fn main() {
(0..3)
.map(|i| {
struct S {
v: usize,
}
S { v: i }
})
.collect::<Vec<_>>();
}
我认为每个闭包调用都会定义一个新的结构类型(及其实例),因此结果无法收集为某种单一类型的向量,但似乎
S
不是那么本地。
这在幕后到底是如何工作的?我想要严格的解释,例如指向 The Rust Reference 页面的链接,因此添加了 #language-lawyer
标签。
解读1
//`S` is *global* in some sense.
struct S {
v: usize,
}
//Every invocation of the closure just creates a new instance of the type `S`.
for i in 0..3 {
vec.push(S { v: 0 });
}
解读2
{
//Every invocation of the closure declares a new struct type
// which is local to the invocation.
struct __S_anonymous_01 {
v: usize,
}
//And it then creates a new instance of that type.
vec.push(__S_anonymous_01 { v: 0 });
}
{
struct __S_anonymous_02 {
v: usize,
}
vec.push(__S_anonymous_02 { v: 1 });
}
{
struct __S_anonymous_03 {
v: usize,
}
vec.push(__S_anonymous_03 { v: 2 });
}
//And `__S_anonymous_{01|02|03}` are all different
// though they have the same structure
// because Rust doesn't support duck typing.