Advertisement
Guest User

Untitled

a guest
Sep 28th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. // Our request type. Owned by someone else
  2. trait Request {
  3. fn url(&self) -> String;
  4. }
  5.  
  6. trait IntoRequest<R> where R: Request {
  7. fn into_request(self) -> R;
  8. }
  9.  
  10. impl <R, I> IntoRequest<R> for I where
  11. R: Request,
  12. I: Into<R> {
  13. fn into_request(self) -> R {
  14. self.into()
  15. }
  16. }
  17.  
  18. struct IndexRequest;
  19. impl Request for IndexRequest {
  20. fn url(&self) -> String {
  21. "/index".to_string()
  22. }
  23. }
  24.  
  25. struct MappingRequest;
  26. impl Request for MappingRequest {
  27. fn url(&self) -> String {
  28. "/mapping".to_string()
  29. }
  30. }
  31.  
  32. struct TypeToIndex {
  33. pub id: i32
  34. }
  35.  
  36. // For types we don't own, we need to implement IntoRequest<R> directly
  37. impl <'a> IntoRequest<IndexRequest> for (&'a str, TypeToIndex) {
  38. fn into_request(self) -> IndexRequest {
  39. IndexRequest
  40. }
  41. }
  42.  
  43. // For types we do own, we can implement Into<R> and have IntoRequest<R> automagically derived
  44. impl Into<IndexRequest> for TypeToIndex {
  45. fn into(self) -> IndexRequest {
  46. IndexRequest
  47. }
  48. }
  49.  
  50. impl Into<MappingRequest> for TypeToIndex {
  51. fn into(self) -> MappingRequest {
  52. MappingRequest
  53. }
  54. }
  55.  
  56. // A function that takes a Request and does some stuff
  57. fn request<R>(req: R) where
  58. R: Request {
  59. println!("{}", req.url());
  60. }
  61.  
  62. fn main() {
  63. request::<IndexRequest>(("idx", TypeToIndex { id: 1 }).into_request());
  64. request::<IndexRequest>(TypeToIndex { id: 1 }.into_request());
  65. request::<MappingRequest>(TypeToIndex { id: 1 }.into_request());
  66.  
  67. request(IndexRequest);
  68. request(MappingRequest);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement