Last active
August 22, 2016 10:05
-
-
Save KodrAus/6b0e714df74aa9323a4a3ce6cb4c7e83 to your computer and use it in GitHub Desktop.
Rust Modules
This file contains hidden or 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
mod entities { | |
//This module is public to anyone outside entities | |
pub mod traits { | |
pub trait Entity { | |
fn id(&self) -> i32; | |
fn title(&self) -> &str; | |
} | |
} | |
//This module is private to anyone outside entities | |
mod people { | |
//We can use 'super' and 'self' to navigate through the module tree | |
use super::traits::Entity; | |
//The id and title fields on Person are only visible in the people module | |
pub struct Person { | |
id: i32, | |
title: String | |
} | |
impl Person { | |
pub fn new(id: i32, title: &str) -> Person { | |
Person { | |
id: id, | |
title: title.to_string() | |
} | |
} | |
} | |
impl Entity for Person { | |
fn id(&self) -> i32 { | |
self.id | |
} | |
fn title(&self) -> &str { | |
&self.title | |
} | |
} | |
} | |
//We can re-export module members with different visibility | |
pub use self::people::*; | |
} | |
use entities::traits::*; | |
use entities::Person; | |
fn main() { | |
let person = Person::new(1, "Jan"); | |
println!("{}: {}", person.id(), person.title()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment