Rust 为什么add_cart会抱怨出现错误?

Rust 为什么add_cart会抱怨出现错误?,rust,Rust,试图理解为什么merchant.add\u cart()在抱怨,而merchant.add\u product()可以。购物车和产品都或多或少包含相同的结构 use std::collections::HashMap; #[derive(Debug, Clone)] struct Merchant<'a> { id: u64, name: String, products: HashMap<u64, &'a Product>, c

试图理解为什么
merchant.add\u cart()
在抱怨,而
merchant.add\u product()
可以。
购物车
产品
都或多或少包含相同的结构

use std::collections::HashMap;

#[derive(Debug, Clone)]
struct Merchant<'a> {
    id: u64,
    name: String,
    products: HashMap<u64, &'a Product>,
    carts: HashMap<u64, &'a Cart>,
}

impl<'a> Merchant<'a> {
    pub fn new(id: u64, name: String) -> Merchant<'a> {
        Merchant {
            id,
            name,
            products: HashMap::new(),
            carts: HashMap::new(),
        }
    }

    pub fn add_product(&mut self, product: &'a Product) {
        self.products.insert(product.id, product);
    }

    pub fn add_cart(&mut self, cart: &'a Cart) {
        self.carts.insert(cart.id, cart);
    }
}

#[derive(Debug, Clone)]
struct Product {
    id: u64,
    name: String,
    amount_in_cents: u64,
}

impl Product {
    pub fn new(id: u64, name: String, amount_in_cents: u64) -> Product {
        Product {
            id,
            name,
            amount_in_cents,
        }
    }
}

#[derive(Debug, Clone)]
struct Cart {
    id: u64,
}

impl Cart {
    pub fn new(id: u64) -> Cart {
        Cart { id }
    }
}

fn main() {
    let apple = Product::new(1, String::from("Apple"), 10000);
    let orange = Product::new(2, String::from("Orange"), 20000);
    let guava = Product::new(3, String::from("Guava"), 30000);

    let mut merchant = Merchant::new(1, String::from("Oak Market"));

    merchant.add_product(&apple);
    merchant.add_product(&orange);
    merchant.add_product(&guava);

    let cart = Cart::new(1);
    merchant.add_cart(&cart);
}

当我编译代码时,使用
rustc 1.31.0

时,完整的错误消息如下:

   |
70 |     merchant.add_cart(&cart);
   |                        ^^^^ borrowed value does not live long enough
71 | }
   | - `cart` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created
最后一行是告诉你你的问题。您在
merchant
之前声明了
apple
orange
guava
,因此它们比
merchant
寿命长,因此可以存储对它们的引用。但是,您在
商户
之后声明了
购物车
,因此
商户
的有效期超过了它,因此您无法存储对它的引用


请注意,您的代码将在Rust 2018版中编译,原因是非词法生命周期,已解释。

当我编译您的代码时,完整的错误消息如下:

   |
70 |     merchant.add_cart(&cart);
   |                        ^^^^ borrowed value does not live long enough
71 | }
   | - `cart` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created
最后一行是告诉你你的问题。您在
merchant
之前声明了
apple
orange
guava
,因此它们比
merchant
寿命长,因此可以存储对它们的引用。但是,您在
商户
之后声明了
购物车
,因此
商户
的有效期超过了它,因此您无法存储对它的引用


请注意,您的代码将在Rust 2018版中编译,因为非词汇生存期,解释道。

您的代码在1.31.0版上编译-这很奇怪。我使用的是1.31.0,但我仍然看到错误@orđeZeljić:只有在启用2018版的情况下才会出现。@ChristianFazzini是的,谢谢。顺便说一句,NLL很棒。你的代码在1.31.0上编译-这很奇怪。我使用的是1.31.0,但我仍然看到错误@orđeZeljić:只有在启用2018版的情况下才会出现。@ChristianFazzini是的,谢谢。顺便说一句,NLL很棒。