0

Is it possible to convert two &str to a &(String, String)?

I specifically have a HashMap that has the tuple (String, String) as key, and I would like to lookup the map without cloning the &str.

Consider the following code:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(("Hello".to_owned(), "World".to_owned()), 42);
    
    println!("{:?}", get("Hello", "World", &map));
}

fn get<'a>(id_1: &str, id_2: &str, map: &'a HashMap<(String, String), i32>) -> Option<&'a i32> {
    // Do this without cloning/to_string
    let key: &(String, String) = &(id_1.to_string(), id_2.to_string());
    
    map.get(key)
}
Elias
  • 3,592
  • 2
  • 19
  • 42
  • The accepted answer in the dupe shows how you can call `.get()` without needing to construct a `(String, String)` (which would require copying from the `&str`s. – kmdreko Jul 04 '22 at 17:34
  • @kmdreko The answer in the dupe does not address my question if I can convert two &str to &(String, String)... or am I lost? – Elias Jul 04 '22 at 17:41
  • [Here](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ab8116ef8b2639abe8c96b4c0121540a) is the dupe applied to your usecase. You cannot construct a `&(String, String)` from two `&str`s without copying, its simply not possible. But what you can do is call `.get()` without copying by using some trickery with the `Borrow` trait. – kmdreko Jul 04 '22 at 18:00
  • @kmdreko Ah, I see. I suppose that gives the solution to my problem (although not directly answering the question). Thank though, the dupe seemed quite complicated and I'm happy I have a working example I can reference :) – Elias Jul 04 '22 at 18:09

0 Answers0