2

Take the following code snippet (has to be run in cargo, so you can add the serde feature to 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);
}

It yields this error when compiling:

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

And this note:

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

Now, I understand that I need to make 'a live shorter than 'de, but how can I do that? I don't know where the 'de lifetime is defined. I tried to use a colon like this:

'de: 'a

But that didn't work.

Paul Razvan Berg
  • 16,949
  • 9
  • 76
  • 114
  • 2
    Since the lifetime `'de` doesn't appear in the code you posted, there must be an important piece of code missing. Please add the relevant code, and show the full compiler error. – Aloso Mar 22 '20 at 00:20
  • 1
    @Aloso that's the thing, I don't know where `'de` is. It doesn't appear in my source code either. – Paul Razvan Berg Mar 22 '20 at 01:02
  • The error message should tell you the **file, line number and column** (e.g. `--> src/main.rs:29:18`) – Aloso Mar 22 '20 at 02:59
  • Oh yeah, sorry, the error is concerning this line: `pub trades: Vec>` – Paul Razvan Berg Mar 22 '20 at 12:48
  • 1
    Does this answer your question? [Why can Serde not derive Deserialize for a struct containing only a &Path?](https://stackoverflow.com/questions/56394620/why-can-serde-not-derive-deserialize-for-a-struct-containing-only-a-path) – MaxV Mar 23 '20 at 17:27

1 Answers1

7

Please check that one

TL;DR

#[derive(Debug, Deserialize)]
pub struct TradeTable<'a> {
    #[serde(borrow)]
    pub trades: Vec<Trade<'a>>,
}
MaxV
  • 2,601
  • 3
  • 18
  • 25
  • 3
    If [you suspect something is a duplicate](https://stackoverflow.com/questions/60794121/cannot-infer-an-appropriate-lifetime-for-lifetime-parameter-de-due-to-conflic?noredirect=1#comment107604126_60794121), please do not answer it. Instead, vote to close it as a duplicate. – Shepmaster Mar 23 '20 at 18:53