【问题标题】:How can I iterate on a Bevy Query and keep a reference to the iterated value so that I can use it later?如何迭代 Bevy 查询并保留对迭代值的引用,以便以后可以使用它?
【发布时间】:2020-12-21 19:10:14
【问题描述】:

我在empty 变量中有一个借用,我想延长它的寿命。在注释的代码块中,我尝试解决它,但参考不再可用。我必须再次循环循环才能找到匹配项才能对其采取行动。

如何遍历查询以查找最佳匹配,然后在我知道它是最佳匹配后对其进行操作,而无需循环再次找到它?

use bevy::prelude::*;

struct Person;
struct Name(String);

fn main() {
    App::build()
        .add_default_plugins()
        .add_startup_system(startup.system())
        .add_system(boot.system())
        .run();
}

fn boot(mut query: Query<(&Person, &mut Name)>) {
    let mut temp_str = String::new();
    let mut empty: Option<&mut Name> = None;
    for (_p, mut n_val) in &mut query.iter() {
        if n_val.0.to_lowercase() > temp_str.to_lowercase() {
            temp_str = n_val.0.clone();
            empty = Some(&mut n_val);
        }
    }
    println!("{}", temp_str);
    if let Some(n) = empty {
        // ...
    }
    // for (_p, mut n_val) in &mut query.iter() {
    //     if n_val.0 == temp_str {
    //         n_val.0 = "a".to_string();
    //     }
    // }
}

fn startup(mut commands: Commands) {
    commands
        .spawn((Person, Name("Gene".to_string())))
        .spawn((Person, Name("Candace".to_string())))
        .spawn((Person, Name("Zany".to_string())))
        .spawn((Person, Name("Sarah".to_string())))
        .spawn((Person, Name("Carl".to_string())))
        .spawn((Person, Name("Robert".to_string())));
}

Cargo.toml:

[package]
name = "sample"
version = "0.1.0"
authors = [""]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bevy = "0.1.3"

具体错误:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:17:33
   |
17 |     for (_p, mut n_val) in &mut query.iter() {
   |                                 ^^^^^^^^^^^-
   |                                 |          |
   |                                 |          temporary value is freed at the end of this statement
   |                                 creates a temporary which is freed while still in use
...
24 |     if let Some(n) = empty {
   |                      ----- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

error[E0597]: `n_val` does not live long enough
  --> src/main.rs:20:26
   |
20 |             empty = Some(&mut n_val);
   |                          ^^^^^^^^^^ borrowed value does not live long enough
21 |         }
22 |     }
   |     - `n_val` dropped here while still borrowed
23 |     println!("{}", temp_str);
24 |     if let Some(n) = empty {
   |                      ----- borrow later used here

【问题讨论】:

  • 我对贝维一无所知,但你可以试试let mut iter = query.iter(); for (_p, mut n_val) in &amp;mut iter {

标签: rust bevy


【解决方案1】:

You cannot extend the lifetime of a reference,但这不是你的问题,错误是temporary value dropped while borrowed,所以你必须延长临时的生命周期。

如果您想知道什么是临时的,编译器还会在错误消息中指出(字面意思):query.iter()。这是一个函数调用,返回的值没有绑定到任何东西,所以编译器为此创建了一个临时值。然后,您使用对该临时文件的引用进行迭代。当for 循环结束时,临时对象将被删除,并且对其的任何引用生存期都会到期。

解决方案是将临时变量绑定到局部变量。这样您就可以将对象的生命周期延长到变量的范围:

let mut iter = query.iter();
for (_p, n_val) in &mut iter {
    if n_val.0.to_lowercase() > temp_str.to_lowercase() {
        temp_str = n_val.0.clone();
        empty = Some(n_val);
    }
}

PS:我发现迭代&amp;mut iter 的模式很奇怪。我希望iter() 的返回直接实现IteratorIntoIterator,但它看起来像this is not the case

【讨论】:

  • @VCD_WL:您正在存储对n_val 的引用,这是for 循环的局部变量,因此它无法转义该块。尝试存储 n_val 本身,我认为它已经是一个参考:empty = Some(n_val);
  • 做到了!哇,我在这里还有一些学习要做,但这给了我方向。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-10-28
  • 2014-02-26
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
相关资源
最近更新 更多