'Is there a way to implement the same thing for lots of structs automatically?

As you can see, all the types below have the same structure:

type Response = rtsp_types::Response<Body>;

struct PlayResponse(Response);
struct DescribeResponse(Response);
struct SetupResponse(Response);
struct PauseResponse(Response);
struct TeardownResponse(Response);
struct RecordResponse(Response);
struct UnauthorizedResponse(Response);

And I want to do the same implementation for them:

impl From<Response> for PlayResponse {
    fn from(response: Response) -> Self {
        PlayResponse(response)
    }
}

impl From<Response> for DescribeResponse {
    fn from(response: Response) -> Self {
        DescribeResponse(response)
    }
}

//...

but I don't want to be repetitive.

I know that I could do an enum with all of them, but this solution does not apply to my problem for reasons that are too large to put here.

What would be the be best way to implement From for all these structs, just like the example implementation I did? Macros? Isn't there a way to do a generic implementation over T?



Solution 1:[1]

You can use the duplicate crate to easily do this:

use duplicate::duplicate;

type Response = rtsp_types::Response<Body>;

duplicate!{
    [
        Name;
        [PlayResponse];
        [DescribeResponse];
        [SetupResponse];
        [PauseResponse];
        [TeardownResponse];
        [RecordResponse];
        [UnauthorizedResponse];
    ]
    struct Name(Response);
    impl From<Response> for Name {
        fn from(response: Response) -> Self {
            Name(response)
        }
    }
}

This will both declare each struct and its implementation, substituting Name for the name of each struct.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1