Reputation: 34924
I have the following code:
extern crate serialize;
use std::collections::TreeMap;
use serialize::json;
use serialize::json::ToJson;
use serialize::json::Json;
fn main() {
let mut tree_map = get_tree_map(); // : TreeMap<String, String>
let mut tree_map2 = tree_map.iter().map(|k, v| (k, v.to_json())); //error the type of this value must be known in this context
let json1 = json::Object(tree_map2);
}
I want to convert tree_map
to json. I tried to do it by converting it to TreeMap<String, Json>
but failed. How can I do that?
Upvotes: 1
Views: 422
Reputation: 65822
The closure you passed to map
takes two parameters, but it should take a single parameter that is a tuple type, because iter()
returns an iterator over tuples (see Trait Implementations on Entries). Change |k, v|
to |(k, v)|
to fix this. (I found this by adding explicit type annotations on k
, v
: the compiler then complained about the closure not having the right number of parameters.)
There are some other errors however. Instead of using iter()
, you might want to use into_iter()
to avoid cloning the String
s if you don't need the TreeMap<String, String>
anymore. Also, you should add .collect()
after .map(...)
to turn the iterator into a TreeMap
. The compiler will automatically infer the type for tree_map2
based on the requirements for json::Object
.
fn main() {
let mut tree_map = get_tree_map(); // : TreeMap<String, String>
let mut tree_map2 = tree_map.into_iter().map(|(k, v)| (k, v.to_json())).collect();
let json1 = Json::Object(tree_map2);
}
Upvotes: 2