鉴于这个 Rust 示例(在此处找到):
struct Dog {
name: ~str
}
fn dogshow() {
let dogs: [~Dog * 3] = [
~Dog { name: ~"Spot" },
~Dog { name: ~"Fido" },
~Dog { name: ~"Snoopy" },
];
// let winner: ~Dog = dogs[1]; // this would be a compile time error.
// can't assign another name to a
// uniquely owned (`~`) pointer.
for dogs.each |dog| { // WTF? `dog` is a second pointer to dogs[x].
// That's not supposed to be allowed by `~` pointers.
// why is this not a compile time error?
println(fmt!("Say hello to %s", dog.name));
}
}
dog
参数是什么类型的指针.each
?
变量的声明dog
似乎打破了唯一拥有的指针 ( ~
) 一次只能有一个名称的规则。
如何在不破坏唯一拥有的 ( ) 指针规则的情况下循环遍历dogs
并将每只狗分配给变量名?dog
~
dog
在这种情况下是Rust引用(因此允许另一个名称表示借用的指针)?如果是这样,我们怎么知道?Rust 引用应该使用&
语法,不是吗?