rust - 包含一段数据和被引用数据的结构中的生命周期

标签 rust reference lifetime

这个问题在这里已经有了答案:





Why can't I store a value and a reference to that value in the same struct?

(3 个回答)


1年前关闭。




我正在写一个小卡片反人类克隆供个人使用,并将其作为学习 Rust 的机会。我目前有以下结构:

// game.rs
pub struct Game<'c> {
    deck: Deck,
    players: Vec<Player<'c>>,
    current_czar_index: usize,
}
// player.rs
pub struct Player<'c> {
    pub hand: Vec<&'c Card>,
    pub max_hand_size: usize,
    pub is_czar: bool,
    pub score: u8,
    pub name: String,
}
// deck.rs
struct DiscardPile {
    pub white: Mutex<Vec<usize>>,
    pub black: Mutex<Vec<usize>>,
}

pub struct Deck {
    white: Vec<Card>,
    black: Vec<Card>,
    pub used_sets: Vec<String>,
    discard_pile: DiscardPile,
}
// card.rs
pub struct Card {
    pub text: String,
    pub uuid: Uuid,
    pub pick: Option<u8>,
}
还有一些其他的(即用于读取 JSON 文件的 set),但它们不相关。
我在 game.rs 中有一个函数
    pub fn deal_hands(&self) -> Result<(), Box<dyn std::error::Error>> {
        for player in &mut self.players {
            while player.hand.len() < player.max_hand_size {
                player.add_card(self.deck.draw_white().unwrap())?;
            }
        }
        Ok(())
    }
这给了我以下错误:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/game.rs:42:31
   |
42 |                 player.add_card(self.deck.draw_white().unwrap())?;
   |                                           ^^^^^^^^^^
   |
它特别说它期待&mut Player<'_>但找到了 &mut Player<'c> 的生命周期.
HERE如果您想直接查看代码。
我该如何解决这样的终身错误,还是需要重新考虑我的架构?

最佳答案

架构对我来说似乎很好。您可能只是在某处错过了生命周期参数的传递。
我不完全确定,但我相信问题可能是 .draw_white()正在返回 Option<&Card>并且不清楚所包含的 Card 的生命周期是多少应该。我相信,任何时候你归还借来的值(value),你都必须为借来的值(value)附加一个生命周期。否则,借用检查器无法判断借用值将存在多长时间。
也许尝试以下定义 .draw_white()反而

pub fn draw_white<'a>(&self) -> Option<&'a Card> {
然后你需要调整 deal_hands()像下面这样。 (努力找出正确的语法,但我认为它是这样的。)
    pub fn deal_hands(&self) -> Result<(), Box<dyn std::error::Error>> {
        for player<'c> in &mut self.players {
            while player.hand.len() < player.max_hand_size {
                player.add_card(self.deck.draw_white<'c>().unwrap())?;
            }
        }
        Ok(())
    }

关于rust - 包含一段数据和被引用数据的结构中的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64602936/

相关文章:

java - 尝试结束 session 时应用程序崩溃..空对象引用

rust - 如何为引用自身但不改变自身的迭代器的关联类型指定生命周期?

iterator - 将迭代器 Item 类型不匹配解析为具有显式生命周期的指针

rust - sdl2-sys 无法编译 - 无法执行链接器 : No such file or directory

Rust 对临时值的引用不报告错误

c# - 在 C# 中存储 ref

perl - 如何将函数返回值从引用转换为数组?

GIT 存储说明

rust - 调用 Clap 的 get_matches 后如何显示帮助?

rust - 如何在 Unsafe Rust 中传递未初始化的变量地址