Skip to content

Instantly share code, notes, and snippets.

@KodrAus
Last active October 31, 2016 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KodrAus/2fd287e586fe70863fcbc8e9d791a143 to your computer and use it in GitHub Desktop.
Save KodrAus/2fd287e586fe70863fcbc8e9d791a143 to your computer and use it in GitHub Desktop.
elastic API
// 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);
}
@KodrAus
Copy link
Author

KodrAus commented Oct 31, 2016

Note this needs to be rethought given most types won't e part of this library. elastic_types is probably going to need an elastic_requests feature to implement Into<IndexRequest> and Into<MappingRequest>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment