Trait Bound for "From<T> for u64"

Hello everyone,

I was wondering if there is a way to define a trait bound that ensures T implements From<T> for u64, like

impl From<T> for u64 {
    fn from(val: T) -> u64 {
    ...
    }
}

I tried the following, which obviously did not work. (Function functionality shows just the use of From trait)

pub fn foo<T: u64::From<T>> (val_1: u64, val_2: T)  {
    ...
    let unsgnd = u64::from(val_2)
    ...
}

Thanks for your help.

The trait you are looking for is Into, so you can specify T : Into<u64>. This is preferred to defining trait bounds in terms of From, since everything that implements From implements Into, but some things just implement Into.

1 Like

To answer the question as asked: you use a where clause to apply free-form constraints to a function or struct.

Example (don't use this)
fn foo<T>(val_1: u64, val_2: T)
where
    u64: From<T>

However, @jameseb7 is correct that Into is preferable to From for bounds because it's easier to satisfy. This also means you should change the body of your function to use val_2.into() instead of u64::from(val_2).

4 Likes

Yes, that's exactly what I needed. Thank you both very much for the quick help!

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.