Hi,
So as the title says, I have a small example here:
Code is also listed below:
use std::collections::BTreeMap;
enum MyType {
Bool(bool),
Int(i32),
Str(String)
}
// A unified api which allows to encode any rust type
fn write<T: Into<MyType>>(val: T) {
// Encoding goes here
}
impl Into<MyType> for bool {
fn into(self) -> MyType {
MyType::Bool(self)
}
}
// error[E0210]: type parameter `T` must be used as the type parameter for some
// local type (e.g. `MyStruct<T>`); only traits defined in the current crate can be
// implemented for a type parameter
impl<T: Into<MyType>> Into<MyType> for HashMap<String, T> {
fn into(self) -> MyType {
unimplemented!();
}
}
impl Into<MyType> for String {
fn into(self) -> MyType {
MyType::Str(self)
}
}
fn dummy_map() -> BTreeMap<String, String> {
let mut m = BTreeMap::new();
m.insert("".to_string(), "".to_string());
m
}
fn main() {
write(true);
write(true);
// Now i want to write a map
let mut my_map = dummy_map();
// my_map.write(my_map); // This does not work
}
Compiler errors with:
error[E0210]: type parameter T
must be used as the type parameter for some local type (e.g. MyStruct<T>
); only traits defined in the current crate can be implemented for a type parameter
Sure i can create a wrapper type like: struct WrapperMap<T>(BTreeMap<String, T>);
and ask users of my library to wrap their types in this wrapper, but that's extra thing that library user has to do.
So i wanted to know if there are other ways where my write
method can accept the BTreeMap
with T as a value ?