Having issues with a Trait and types

I have two structs, S and SS.
I want to have a trait that has a method load, that returns S by building a conversion S::from(SS)

struct SS;

struct S;

impl From<SS> for S {
    fn from(ss: SS) -> Self {
        Self
    }
}

pub trait Tr {
    type Item;
    fn load<T>() -> T
    where
        T: From<Self::Item>;
}

impl Tr for S {
    type Item = SS;
    fn load<S>() -> S {
        let ss = SS;
        S::from(ss)
    }
}

However, I get:

error[E0308]: mismatched types
  --> src/main.rs:18:17
   |
16 |     fn load<S>(s: &str) -> S {
   |             - this type parameter
17 |         let ss = SS {};
18 |         S::from(ss)
   |                 ^^ expected type parameter `S`, found struct `SS`
   |
   = note: expected type parameter `S`
                      found struct `SS`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `asd`

To learn more, run the command again with --verbose.

Playground link: Rust Playground

fn load<S>(s: &str) -> S

means that S is a fresh type parameter. It's not the concrete S type. And you didn't declare that S: From<SS>. Why don't you call the type parameter T, like in your trait? That would be much clearer.


impl Tr for S {
    type Item = SS;
    fn load<T: From<Self::Item>>() -> T {
        let ss = SS;
        T::from(ss)
    }
}

Thanks!

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.