BTreeMap and "returns value referencing data owned by the current function"

Hi there,

In this code:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2c09f787a003629882d82c795557e5b0

I don't understand how my key is linked to the value, they shouldn't share anything at all, the BTreeMap being the only link but it shouldn't trigger this borrowing error.

What am I missing?

It's because you unwittingly said they were linked.

&'a BTreeMap<IdOrRaw<'a>, Data>

Says that the lifetime of the keys is the same as the map. You really want,

&'a BTreeMap<IdOrRaw<'_>, Data>

Which unlinks the two lifetimes

Even with @RustyYato's suggestion, the signature is like this:

fn search_for<'a, 'b>(key: Key, hash: &'a BTreeMap<IdOrRaw<'b>, Data>) -> Option<&'a Data>

This means that to index into the hash map, you need an IdOrRaw<'b>, however your id doesn't live for the full 'b lifetime, so you can't use it to look-up. You will need to add some sort of impl for the Borrow trait to get around this.

Thank you for your answer!

Unfortunately it doesn't change anything:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f37f555bfb67d1c5367e93078490d772

(I changed the the lifetime of IdOrRaw to '_)

Thank you for your answer!

Never used this trait before, there's a first time to anything I guess :smiley: going to read the doc now :slight_smile:

Yeah, I didn't notice that you had a seperate Key type at play. What's happening is that the key: Key doesn't live long enough.

fn search_for<'a, 'b>(key: &'b Key, hash: &'a BTreeMap<IdOrRaw<'b>, Data>) -> Option<&'a Data>

edit: Btw, your IdOrRaw type looks a lot like Cow<'a, str>

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.