繁体   English   中英

“&*” 在 Rust 中有什么作用

[英]What does “&*” do in Rust

我在从 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 中不时出现的常见习语。

  • &在一个表达式中只有一个含义:它接受一个T类型的表达式(它必须是一个位置表达式)并借用一个&T类型的对它的引用。

  • 对于引用, *&相反——它接受一个引用 ( &T ) 并生成T类型的 place 表达式。 但是*可以用不同类型的指针表示不同的东西,因为您可以通过实现Deref来覆盖它。 因为*与一些编译器魔法有关,这些魔法会自动取消引用Deref::deref的返回值, Deref::deref您可以借用*的结果,通过使用&运算符将其转换回普通引用。

所以&*foo是一种显式地重新借用“任何类型的指向T的指针”作为&T ,相当于手动调用Deref::deref(&foo)

(以上解释也适用于&mut借用 - 只需将&替换为&mut并将DerefDerefMut 。)

在示例中不清楚您链接的是什么entities ,但它可能是某种智能指针,其中join()方法需要一个简单的引用。 对于另一个需[&str]::concat示例,请考虑使用[&str]::concatString与一些&str连接起来:

// 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

也可以看看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM