Hashmap, поддерживающий String и & str - PullRequest
1 голос
/ 20 июня 2019

Как определить HashMap, поддерживающий как String, так и &str в его ключе и содержимом?Я попробовал следующее:

fn mapping<T: Into<String>>() -> HashMap<T, T> {
  let mut map: HashMap<T, T> = HashMap::new();
  map.insert("first_name", "MyFirstName");
  map.insert("last_name".to_string(), "MyLastName".to_string());
  map
}

fn main() {
  let mut mapping = mapping();
}

Но он не компилируется, говоря:

error[E0599]: no method named `insert` found for type `std::collections::HashMap<T, T>` in the current scope
error[E0277]: the trait bound `T: std::cmp::Eq` is not satisfied
error[E0277]: the trait bound `T: std::hash::Hash` is not satisfied

1 Ответ

2 голосов
/ 20 июня 2019

Встроенный способ абстрагироваться от того, заимствованы или принадлежат данные, - Cow.

use std::borrow::Cow;
use std::collections::HashMap;

fn mapping() -> HashMap<Cow<'static, str>, Cow<'static, str>> {
    let mut map = HashMap::new();
    map.insert("first_name".into(), "MyFirstName".into());
    map.insert("last_name".to_string().into(), "MyLastName".to_string().into());
    map
}

И &str, и String можно преобразовать в Cow<str>, используя .into().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...