首页 > 解决方案 > 由于需求冲突,无法为生命周期参数“de”推断适当的生命周期

问题描述

采取以下代码片段(必须在 cargo 中运行,因此您可以将serde功能添加到num-bigint):

use num_bigint::BigInt;
use serde_derive::Deserialize;
use std::collections::HashMap;

#[derive(Debug, Deserialize)]
pub struct Trade<'a> {
    pub id: &'a str,
    pub price: BigInt,
    pub quantity: BigInt,
}

#[derive(Debug, Deserialize)]
pub struct TradeTable<'a> {
    pub trades: Vec<Trade<'a>>,
}

fn main() {
    let mut ether_trades: Vec<Trade> = Vec::new();
    ether_trades.push(Trade {
        id: "#1",
        price: BigInt::from(100),
        quantity: BigInt::from(2)
    });

    let mut trades: HashMap<&str, Vec<Trade>> = HashMap::new();
    trades.insert("ETH", ether_trades);
    println!("trades: {}", trades);
}

编译时会产生此错误:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements

还有这个注释:

note: first, the lifetime cannot outlive the lifetime `'de` as defined on the impl at 34:17...

现在,我知道我需要让'alive 短于'de,但我该怎么做呢?我不知道'de生命周期在哪里定义。我尝试使用这样的冒号:

'de: 'a

但这没有用。

标签: rustlifetime

解决方案


请检查那个

TL;博士

#[derive(Debug, Deserialize)]
pub struct TradeTable<'a> {
    #[serde(borrow)]
    pub trades: Vec<Trade<'a>>,
}

推荐阅读