First of all, sorry about my English. I’ve reach to a compilation problem when trying to add a value to a HashMap using a &str parameter as the key. This is a simplification of my real code to show the problem.

You can’t use &str as the key to a HashMap because there is no way for the map to know that the key will still exist when it goes to look it up later. You have two options: you could either let the map own the keys by making them of type String or you could limit your code to compile time strings and make them & static str. Actually in the latter case you could use runtime strings if you leak the strings by promising that you’ll never free them. One way to achieve this would be via string interning via internment.

(long story short, there is a lifetime parameter behind each symbol &, and sometimes in some structures as well. Since the latter are more tricky to spot, I suggest you enable the following lint: #![deny(elided_lifetimes_in_paths)])

Besides the bound on the second and third lifetime parameters ('_3 : '_2, i.e., '_3 lives at least as long as '_2), all these parameters are distinct and independent of each other. This makes them incompatible with each other (AFAIK, there is no bivariance in Rust).

Therefore, the type of planet, &'_1 str, is not “compatible” with the type of the keys, &'_3 str.

Solution

What the others have suggested: that the equality between planet‘s lifetime and the keys’ be made explicit (and now that we are at it, let’s make it equal to the other &str lifetimes, since it seems likely that they will be used in the same context anyways. The one lifetime that does not need to be made explicit is the one in the mut borrow of the HashMap):