Implementing Borrow on my own types

My code: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=2d2c7518668c23382b370ba7c4a141f9

I think the issue is something to do with returning a reference, but I don’t know how to fix it.

I have looked at how Borrow is implemented in std, but I can’t figure out how to do this.

The point is not necessary Borrow, but general ownership system. At the fn borrow in your code, it returns a reference of RefKey. But where is that RefKey is stored? In that code, the RefKey first be stored in the call stack, taken its reference for return, and destroyed with the entire stack frame as the function is ended.

I know that, but how do I fix the problem?

I don’t understand how String and &str do it, some compiler trickery?

I need to implement Borrow, as Key is the key for a HashMap.

No magic in String, as they actually stores str in the heap memory they own. But your Key does not store RefKey itself, so it’s not possible to impl Borrow<RefKey> for Key in general.

You don’t, this works perfectly fine.

You have to allocate on the hot get path of my server though, that’s why I want to implement Borrow.

https://docs.rs/hashbrown/0.3.0/src/hashbrown/map.rs.html#740-752

This shows what happens in get.

I can’t help you much unless you give me more information about your problem. You asked how to impl Borrow<RefKey> for Key and the clear answer is it’s not possible. But I guess this is not the problem you want to solve in the end.

I suspected it was not possible… I want to be able to use the HashMap get method with a borrowed key, like you can with &str with a String key.

You may be interested in How to avoid temporary allocations when using a complex key for a HashMap?. Make sure to read all answers.

That’s better, but if smallvec spills you would still need a temporary allocation.

I guess I could not use it, but it would slow down other parts of the code.

Edit: sorry, I guess you mean the borrowed trait object answer?

Indeed.

I am very sorry about that, thanks.

1 Like

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