1

我在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())));
}

货物.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
4

1 回答 1

3

你不能延长引用的生命周期,但这不是你的问题,错误说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:我发现迭代的模式很奇怪&mut iter。我希望iter()实现IteratorIntoIterator直接返回,但看起来情况并非如此

于 2020-09-02T16:03:54.153 回答