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

example with a trait #62

Open
flosse opened this issue Nov 13, 2016 · 2 comments
Open

example with a trait #62

flosse opened this issue Nov 13, 2016 · 2 comments

Comments

@flosse
Copy link

flosse commented Nov 13, 2016

Could you provide an example that uses a Trait? Or do you know a repository where I can find code examples?
Here is what I'd like to do:

extern crate iron;
extern crate mount;
extern crate persistent;

use std::io;
use iron::prelude::*;
use iron::typemap::Key;
use persistent::State;
use mount::Mount;

struct X;

trait Db {
    fn get(&mut self, id: &str) -> Result<X, io::Error>; 
}

struct Server {
    chain: Chain
}

fn create_server<D: Db + Key>(db: D) -> Server {

    let mount = Mount::new();
    let chain = Chain::new(mount);
    chain.link(State::<D>::both(db));

    Server {
        chain: chain
    }
}

struct Store; 

impl Db for Store {
    fn get(&mut self, id: &str) -> Result<X, io::Error> {
        Ok(X{})
    } 
}

impl Key for Store {
    type Value = Store;
}

fn main() {

    let store = Store {};
    let s = create_server(store);
}

edit: renamed issue & changed content

@flosse flosse changed the title example with Arc and Mutex example with a trait Nov 13, 2016
@untitaker
Copy link
Member

I couldn't get it to work, but even if you manage to, you probably don't want to need to know the concrete type of your Db just to be able to retrieve it from the typemap. You probably want to create a concrete type Db that implements Key and contains a Box<DbTrait> (where DbTrait is what you currently call Db) which contains the actual interface. That way you can retrieve whichever Db you use using Db, not the concrete type.

This issue goes away if you use D for fetching your Db, but as far as I understand this requires you to define all of your handlers within create_server.

@flosse
Copy link
Author

flosse commented Nov 14, 2016

Thanks for your reply!
I'll have a look on it but I guess it's harder than I thought :-\

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

No branches or pull requests

2 participants