pellucid
pellucid

Reputation: 293

What's the Rust syntax to use trait and generic in methods?

In general, I want to have a trait(Requestor) which contain one method returning a T in another trait(ResponseWriter).

I searched Google and tried to find the documents, but I can'f find the right syntax for my situation. The compiler says:

T: ResponseWriter;
   |                ^^^^^^^^^^^^^^ expected 1 type argument

However, I can't write T: ResponseWriter<U> instead, it will give me other errors.

So my question is what's the correct the syntax?

    pub trait ResponseWriter<T> {
        fn get_result(&self) -> T;
    }

    pub trait Requestor {
        fn process<T>(&self) -> T
        where
            T: ResponseWriter;
    }

    pub struct Request {
        pub x: String,
    }

    impl Requestor for Request {
        fn process<T>(&self) -> T {
            Response {
                res: format!("{} {}", self.x, "world".to_owned()),
            }
        }
    }

    pub struct Response<T> {
        pub res: T,
    }

    impl<T> ResponseWriter<T> for Response<T> {
        fn get_result(&self) -> T {
            self.res
        }
    }

    let request = Request {
        x: "hello".to_owned(),
    };
    println!("{}", request.process().get_result());

Upvotes: 2

Views: 187

Answers (1)

pellucid
pellucid

Reputation: 293

The code can be rewrote by the associated types. It perfectly fixes the issue and simplified the code.

    pub trait Requestor {
        type Output;

        fn process(&self) -> Self::Output;
    }

    pub struct Request {
        pub x: String,
    }

    impl Requestor for Request {
        type Output = String;

        fn process(&self) -> String {
            format!("{} {}", self.x, "world".to_owned())
        }
    }

    let request = Request {
        x: "hello".to_owned(),
    };
    println!("{}", request.process());

Upvotes: 2

Related Questions