Impl From<Coll<T>> for Value where exists From<T> for Value

The context here is a serde Value module.

I have a Value enum. For all the Value::T primitives I have From<$T> for Value, they work .

For Value::Set, I added impl From<BTreeSet<Value>> for Value {...}, it works.

Is there a way to do:

impl<T> From<BTreeSet<T>> for Value
    where T: ????,
   {
    fn from(val: BTreeSet<T>) -> BTreeSet<Value> {
        let set: BTreeSet<Value> = val.into_iter()
                                    .map(|t| Value::from(t))
                                    .collect();
        Value::from(set)
    }
}

What is the correct where clause for ’ there exists From T for Value’?

For reference, serde json (if im reading it correctly, and I might not be) seems to handle this any->value conversion by actually implementing Serializer on Value and providing an into_value helper. This seems kind of overkill and breaks the symmetry of Value::from(42)

Thanks for your help, this is difficult to google

I would write:

impl<T: Into<Value>> From<BTreeSet<T>> for Value {
    fn from(val: BTreeSet<T>) -> Value {
        Value::Set(val.into_iter().map(Into::into).collect())
    }
}

Playground

serde_json::Value has this impl but for Vec:

1 Like

Hey dtolnay thanks! serde is pretty wild, I’ve definitely leveled up a few times trying to implement it

I guess I missed this because I don’t understand the Into trait. Thankyou!