Skip to content

Instantly share code, notes, and snippets.

@KodrAus
Last active August 22, 2016 10:05
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/6b0e714df74aa9323a4a3ce6cb4c7e83 to your computer and use it in GitHub Desktop.
Save KodrAus/6b0e714df74aa9323a4a3ce6cb4c7e83 to your computer and use it in GitHub Desktop.
Rust Modules
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