从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
&*实体在这里做什么。据我所知,它是在取消引用实体,然后再次引用它?
这是一个显式的重新借用,并且是不时在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()方法需要一个纯引用。对于另一个需SliceConcatExt::concat要这样做String的示例,请考虑使用来串联s和&strs:
// 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
| 归档时间: | 
 | 
| 查看次数: | 131 次 | 
| 最近记录: |