愚蠢的 n00b 试图学习一点 Rust。这是我的程序:
fn main() {
let v = vec![1, 2, 3];
println!("{:?}", v);
println!("{:?}", &v);
}
产生输出:
[1, 2, 3]
[1, 2, 3]
&
有什么意义?我有一半希望它打印一个内存地址。
我最初是在 intro 中被这个抛出的看起来它们正在通过 循环引用。我的猜测是 Rust 做了一些魔术并检测到它是一个向量的内存地址?
最佳答案
What is the point of the &?
正如您推测的那样,&
引用了一个对象。但是,有一个 Debug
implementation for references to Debug
types只是打印出所引用的对象。这样做是因为 Rust 更喜欢值相等而不是引用相等:
impl<'a, T: ?Sized + $tr> $tr for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
}
如果你想打印内存地址,你可以使用{:p}
:
let v = vec![1,2,3];
println!("{:p}", &v);
it looks like they are looping through a reference
for i in foo
语法糖调用 foo
上的 into_iterator
,并且有一个 implementation of IntoIterator
for &Vec
返回对迭代器中项的引用的迭代器:
fn into_iter(self) -> slice::Iter<'a, T> {
self.iter()
}
关于pointers - 对矢量的引用仍打印为矢量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705268/