Created
August 17, 2017 06:49
-
-
Save anonymous/18e1b06c6fb9f8c9ad3c6e414bc44b25 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains 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
#[derive(Debug)] | |
struct User { | |
first_name: &'static str, | |
last_name: &'static str, | |
} | |
impl User { | |
fn new(first_name: &'static str, last_name: &'static str) -> User { | |
User { | |
first_name: first_name, | |
last_name: last_name, | |
} | |
} | |
} | |
#[derive(Debug)] | |
struct State { | |
users: Vec<User>, | |
} | |
impl State { | |
fn new() -> State { | |
State { users: vec![] } | |
} | |
fn add_user(&mut self, first_name: &'static str, last_name: &'static str) { | |
self.users.push(User::new(first_name, last_name)); | |
} | |
fn first(self) -> Option<User> { | |
if self.users.len() > 0 { | |
let user: User = User { ..self.users[0] }; | |
return Some(user); | |
} else { | |
return None; | |
} | |
} | |
} | |
fn main() { | |
let mut state = State::new(); | |
state.add_user("hello", "world"); | |
let first_user = state.first(); | |
match first_user { | |
Some(user) => println!("{} {}", user.first_name, user.last_name), | |
None => println!("No user at that index"), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment