【问题标题】:What does “&*” do in Rust“&*”在 Rust 中做了什么
【发布时间】:2019-06-28 13:00:33
【问题描述】:

我在阅读 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


    【解决方案1】:

    这是一个显式的重借,它是 Rust 中不时出现的常见习语。

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

    • 对于引用,*& 正好相反——它接受一个引用 (&T) 并生成一个 T 类型的位置表达式。但是* 可以用不同类型的指针表示不同的东西,因为您可以通过实现Deref 来覆盖它。因为* 绑定了automatically dereferences the return value of Deref::deref 的一些编译器魔法,所以您可以借用* 的结果,通过使用& 运算符将其转换回普通引用。

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

    (上述解释也适用于&mut借用——只需将&替换为&mut,将Deref替换为DerefMut。)

    在链接的示例中不清楚entities 是什么,但它可能是某种智能指针,其中join() 方法需要一个简单的引用。对于另一个需要这样做的示例,请考虑使用[&str]::concatString 与一些&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
    

    另见

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 2023-02-23
      • 1970-01-01
      • 2014-08-03
      • 2012-02-12
      • 2010-10-26
      • 2019-07-12
      • 2010-11-20
      • 2011-07-24
      相关资源
      最近更新 更多