Imagine the following scenario: an Application can accept different kind of requests, processes them and returns either a response or and error. The different kinds of requests should be variants of an enum, such that we can match on them in a processReqest function. However each request type should have its own associated response and error types.
How can we achieve this in Rust?
trait ReqKind {
type ResponseType;
type ErrorType;
}
struct ImgReq {}
struct ImgRes {}
struct ImgErr {}
impl ReqKind for ImgReq {
type ResponseType = ImgRes;
type ErrorType = ImgErr;
}
struct TextReq {}
struct TextRes {}
struct TextErr {}
impl ReqKind for TextReq {
type ResponseType = TextRes;
type ErrorType = TextErr;
}
enum Requests {
Img(ImgReq),
Text(TextReq),
}
fn processReqest(r: Requests) -> ??? {
match r {
Requests::Img(_) => {
return Ok(ImgRes);
// or return Err(ImgRes)
}
Requests::Text(_) => {
return Err(TextErr);
// or return Ok(TextRes)
}
}
}
Here is what I have so far, but I don't know how we would specify the return type of the processRequest function.
Unless you're using trait objects you can't return different types from a function depending on the input, since you're already using static dispatch for your input you can just unify the return types like you did with the
Requestsenum:Or to make use of the associated types just make your function a method on the trait instead: