Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make (vec) conversions more general #101

Closed
icefoxen opened this issue Dec 12, 2016 · 2 comments
Closed

Make (vec) conversions more general #101

icefoxen opened this issue Dec 12, 2016 · 2 comments

Comments

@icefoxen
Copy link

Specifically, it seems like JsonValue should implement: impl From<Vec<T>> for JsonValue where T: Into<JsonValue> , or something along those lines. The goal would be to implement a new type, do impl From<MyType> for JsonValue, and be able to convert a Vec<MyType> to JsonValue automatically.

There may be analogous conversions possible for containers other than Vec, I can't think of any specific ones right now though.

@icefoxen
Copy link
Author

icefoxen commented Dec 12, 2016

Proof of concept:

#[derive(Debug)]
enum JsonValue {
    Integer(i32),
    Array(Vec<JsonValue>),
}

impl From<i32> for JsonValue {
    fn from(value: i32) -> JsonValue {
        JsonValue::Integer(value)
    }
}


impl<T> From<Vec<T>> for JsonValue where JsonValue: From<T> {
    fn from(value: Vec<T>) -> JsonValue {
        let new_values = value.into_iter().map(From::from).collect();
        JsonValue::Array(new_values)
    }
}


struct MyType(i32);
impl From<MyType> for JsonValue {
    fn from(value: MyType) -> JsonValue {
        JsonValue::Integer(value.0)
    }
}


fn main() {
    let myvalues = vec![MyType(1), MyType(2), MyType(3)];
    let json_array: JsonValue = From::from(myvalues);
    println!("Json array is: {:?}", json_array);
}

@maciejhirsz
Copy link
Owner

This makes perfect sense. I'll try to sneak it in on Sunday.

@maciejhirsz maciejhirsz mentioned this issue Jan 2, 2017
maciejhirsz added a commit that referenced this issue Jan 2, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants