【问题标题】:How do I declare a function that accepts anything that can be turned into HashMap<String,String>如何声明一个接受任何可以转换为 HashMap<String,String> 的函数
【发布时间】:2018-05-24 18:28:57
【问题描述】:

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

struct Fields {
    map: HashMap<String, String>
}

对于人体工程学,我想要一个同时接受&amp;strString 的函数。我读到HashMap 有一个特征FromIterator&lt;(K, V)&gt;,所以在抽象层面上,我可以从 anything 工作,它产生一个对变成字符串的迭代器。

类似地,如果我想要一个接受任何可以转换为String 的函数,我可以使用绑定的T: Into&lt;String&gt;

对于可以转换为字符串的对的迭代器是否可以这样做?从概念上讲:

fn set_map<I: IntoIterator<Item=(Into<String>, Into<String>)>>(fields: I) {
    // ...
}

这个错误与

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`

【问题讨论】:

    标签: function hashmap rust


    【解决方案1】:

    您忘记将Item 的元组元素作为类型(而不是特征)传递。以下应该有效:

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

    ST 两个不同的参数允许您在元组中拥有不同的 Into&lt;String&gt; 类型。

    【讨论】:

    • 我会为元组元素使用两个单独的参数。两个元素是否具有相同的类型无关紧要,只要它们都可以变成字符串即可。
    • 神奇!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2017-12-10
    • 2016-06-27
    • 2014-07-20
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多