I was trying to optimize an allocation out of a BTreeMap lookup and ran into problems. BTreeMap::get() looks like it was meant to solve this problem however it requires using the Borrow trait to work. The problem is that Borrow::borrow requires returning a reference, which effectively requires that the value exists in the original type. This doesn’t work in my case as there is no useful type I can use.

Is there, or is there a need for, some Borrow-like trait which allows returning any T, rather then only &T? This would allow returning a “compatible” type which doesn’t necessarily need to be contained in the “parent” type.

Yeah, this is an issue that crops up from time to time. Indeed there’s a need for a trait that allows returning values. There have been some threads here on this before - I’m on mobile or else I’d try to find them .

In the meantime, can you change your Pub variant to store a Cow<'static, str>? Or you can make it Cow<'a, str> but then the Key enum will gain a lifetime parameter.

Yeah, this is an issue that crops up from time to time. Indeed there’s a need for a trait that allows returning values. There have been some threads here on this before - I’m on mobile or else I’d try to find them .

I have failed to come up with the right keywords. If you could try searching at a better time it would be appreciated.

vitalyd:

In the meantime, can you change your Pub variant to store a Cow<'static, str>? Or you can make it Cow<'a, str> but then the Key enum will gain a lifetime parameter.

This doesn’t really work in my case as the strings are not static. The lifetime parameter also wouldn’t work as there is no reasonable place to bind the lifetime. I could cheat around it via unsafe cast to &'static but would prefer to avoid that.