如何声明一个接受任何可以转换为HashMap <String,String>的函数的函数

Mar*_*ten 2 function hashmap rust

我有一个看起来像这样的结构:

struct Fields {
    map: HashMap<String, String>
}
Run Code Online (Sandbox Code Playgroud)

对于人体工程学,我想要一个接受&str和的功能String.我读到它HashMap有一个特征FromIterator<(K, V)>,所以在抽象层面上,我可以从产生成对的迭代器的任何东西中变成字符串.

类似地,如果我想要一个接受任何可以转换为a的函数的函数String,我可以使用该约束T: Into<String>.

可以对可以转换为字符串的对的迭代器进行相同的操作吗?概念:

fn set_map<I: IntoIterator<Item=(Into<String>, Into<String>)>>(fields: I) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这个错误

error[E0277]: the trait bound `std::convert::Into<std::string::String> + 'static: std::marker::Sized` is not satisfied
 --> src/main.rs:1:1
  |
1 | / fn set_map<I: IntoIterator<Item = (Into<String>, Into<String>)>>(fields: I) {
2 | |     // ...
3 | | }
  | |_^ `std::convert::Into<std::string::String> + 'static` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `std::convert::Into<std::string::String> + 'static`
  = note: only the last element of a tuple may have a dynamically sized type

error[E0038]: the trait `std::convert::Into` cannot be made into an object
 --> src/main.rs:1:1
  |
1 | fn set_map<I: IntoIterator<Item = (Into<String>, Into<String>)>>(fields: I) {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::Into` cannot be made into an object
  |
  = note: the trait cannot require that `Self : Sized`
Run Code Online (Sandbox Code Playgroud)

lje*_*drz 5

你忘了将Item元组元素作为类型(而不是特征)传递.以下应该有效:

fn set_map<S: Into<String>, T: Into<String>, I: IntoIterator<Item=(S, T)>>(fields: I) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

两个不同的参数ST,而不只是一个让你有不同的Into<String>元组的类型.