Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define types for document id and database name #4

Closed
cmbrandenburg opened this issue Sep 14, 2015 · 2 comments
Closed

Define types for document id and database name #4

cmbrandenburg opened this issue Sep 14, 2015 · 2 comments
Assignees

Comments

@cmbrandenburg
Copy link
Member

Define DocumentId and DatabaseName types. These types would replace the &str type currently used for identifying documents and databases, thereby making our crate's API more type-safe.

@cmbrandenburg cmbrandenburg self-assigned this Sep 14, 2015
@cmbrandenburg cmbrandenburg changed the title Define type for document id Define types for document id and database name Oct 18, 2015
@cmbrandenburg
Copy link
Member Author

This can be conveniently done using traits.

In the example below, our crate defines the DatabaseName trait and the DatabaseLiteral type, and the application defines the Db type to implement DatabaseName.

Doing it this way allows applications to specify a plain string literal (using the DatabaseLiteral type), while also allowing applications to implement custom database name types of unlimited complexity.

trait DatabaseName {
    fn database_name(&self) -> &str;
}

struct DatabaseLiteral<'a>(&'a str);

impl<'a> DatabaseName for DatabaseLiteral<'a> {
    fn database_name(&self) -> &str {
        let DatabaseLiteral(s) = *self;
        s
    }
}

enum Db {
    Alpha,
    Bravo(String),
}

impl DatabaseName for Db {
    fn database_name(&self) -> &str {
        match *self {
            Db::Alpha => "alpha",
            Db::Bravo(ref s) => s,
        }
    }
}

fn head_database<D>(name: D) -> () where D: DatabaseName {
    println!("{}", name.database_name());
}

head_database(Db::Alpha);
head_database(Db::Bravo("hello".to_string()));
head_database(DatabaseLiteral("foo"));

@cmbrandenburg
Copy link
Member Author

Resolved in this commit: 9ec3eed.

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

No branches or pull requests

1 participant