gpt4 book ai didi

rust - 为什么 add_cart 提示错误?

转载 作者:行者123 更新时间:2023-11-29 08:24:40 27 4
gpt4 key购买 nike

试图理解为什么 merchant.add_cart() 提示而 merchant.add_product() 没问题。 CartProduct 都包含或多或少相同的结构

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);
}

merchant.add_cart(&cart); 正在提示

cart does not live long enough: borrowed value does not live long enough

使用 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 之前声明了 appleorangeguava,因此它们的生命周期比 merchant 长,因此可以存储对它们的引用。但是,您在 merchant 之后声明了 cart,因此 merchant 比它长,因此您无法存储对它的引用。

请注意,由于非词法生命周期,您的代码将在 Rust 2018 版中编译,已解释 here .

关于rust - 为什么 add_cart 提示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53681099/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com