Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Our request type. Owned by someone else
- trait Request {
- fn url(&self) -> String;
- }
- trait IntoRequest<R> where R: Request {
- fn into_request(self) -> R;
- }
- impl <R, I> IntoRequest<R> for I where
- R: Request,
- I: Into<R> {
- fn into_request(self) -> R {
- self.into()
- }
- }
- struct IndexRequest;
- impl Request for IndexRequest {
- fn url(&self) -> String {
- "/index".to_string()
- }
- }
- struct MappingRequest;
- impl Request for MappingRequest {
- fn url(&self) -> String {
- "/mapping".to_string()
- }
- }
- struct TypeToIndex {
- pub id: i32
- }
- // For types we don't own, we need to implement IntoRequest<R> directly
- impl <'a> IntoRequest<IndexRequest> for (&'a str, TypeToIndex) {
- fn into_request(self) -> IndexRequest {
- IndexRequest
- }
- }
- // For types we do own, we can implement Into<R> and have IntoRequest<R> automagically derived
- impl Into<IndexRequest> for TypeToIndex {
- fn into(self) -> IndexRequest {
- IndexRequest
- }
- }
- impl Into<MappingRequest> for TypeToIndex {
- fn into(self) -> MappingRequest {
- MappingRequest
- }
- }
- // A function that takes a Request and does some stuff
- fn request<R>(req: R) where
- R: Request {
- println!("{}", req.url());
- }
- fn main() {
- request::<IndexRequest>(("idx", TypeToIndex { id: 1 }).into_request());
- request::<IndexRequest>(TypeToIndex { id: 1 }.into_request());
- request::<MappingRequest>(TypeToIndex { id: 1 }.into_request());
- request(IndexRequest);
- request(MappingRequest);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement