从Rust库中阅读文档时遇到了这段代码:
for (ent, pos, vel) in (&*entities, &mut pos_storage, &vel_storage).join() {
println!("Processing entity: {:?}", ent);
*pos += *vel;
}
原始链接:https : //slide-rs.github.io/specs/08_join.html
&* entities在这里做什么。据我所知,它是在取消引用实体,然后再次引用它?
这是一个明显的重新借用,并且是不时在Rust中弹出的一个常见习语。
&
在表达式中只有一个含义:它接受type的表达式(必须是place表达式)T
并借用type的引用&T
。
对于引用,*
则执行相反的操作&
-引用(&T
)并生成type的place表达式T
。但是*
用不同种类的指针可能意味着不同的事情,因为您可以通过实现来覆盖它Deref
。由于使用*
了某种会自动取消引用的返回值的Deref::deref
编译器魔术中的联系,因此您可以*
使用&
运算符借用的结果,将其返回为纯引用。
因此,&*foo
有一种方法可以显式地重新借用“任何类型的指针T
” &T
,这相当于手动调用Deref::deref(&foo)
。
(以上解释也适用于&mut
借入-只需更换&
与&mut
和Deref
带DerefMut
。)
在链接的示例中尚不清楚entities
,但是它可能是某种智能指针,其中该join()
方法需要一个纯引用。对于需要此操作的另一个示例,请考虑使用[&str]::concat
将aString
与某些&str
s连接:
// I want to concatenate this with some other strings
let s = String::from("Amelia");
// The following won't compile: you can't make an array of &str and String
assert_eq!(["Hello", ", ", s].concat(), "Hello, Amelia"); // WRONG
// However, &*s takes a reference to the str pointed to by s.
assert_eq!(["Hello", ", ", &*s].concat(), "Hello, Amelia"); // OK
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句