Last active
October 31, 2016 21:23
-
-
Save KodrAus/2fd287e586fe70863fcbc8e9d791a143 to your computer and use it in GitHub Desktop.
elastic API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note this needs to be rethought given most types won't e part of this library.
elastic_types
is probably going to need anelastic_requests
feature to implementInto<IndexRequest>
andInto<MappingRequest>
.