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

Hi there,

In this code:

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:

(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.