Is it possible to write a generic function for this case?

I'm struggling coming up with trait bounds for a generic function. I'm trying to write a function that takes types that can be converted to a Value. Value implements From for a couple of types. Is there a way to specify this so the following example would work or is there a better way to do this?

fn convert_to_value<T: ???>(to_convert: T) -> Value {
    Value::from(to_convert)
}

Thanks in advance for your help!

fn convert<T>(v: T) -> Value where Value: From<T> {
    Value::from(v)
}

But I'd suggest to use v.into() instead, as the stdlib has impl<T, U: From<T>> Into<U> for T.

1 Like

Ah I see, I was trying to find the inverse of From somehow. Didn't know you could specify it like this. Thank you! :slight_smile:

the into version should look like this

fn convert_to_value<T: Into<Value>>(to_convert: T) -> Value {
    to_convert.into()
}

or

fn convert_to_value(to_convert: impl Into<Value>) -> Value {
    to_convert.into()
}
1 Like

to expand on this everything implementing From has automatically an Into implementation however some types can't implement From but have a Into implementation. I run into this once or twice i think it had to do with the 'orphan rule' .

I always thought this is not actually true (anymore) with current orphan rules. Or am I missing something?

2 Likes

Yes, with yhe current orphan rules this isn't true anymore as far as I can tell.

1 Like

True since a half year or so rust got a update witch allows at least most of this cases but at the point i was running into this problems it was still a thing

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.