Skip to content

Instantly share code, notes, and snippets.

@selfup
Forked from anonymous/playground.rs
Last active August 17, 2017 06:55
Show Gist options
  • Save selfup/b7f908220274f2f36b1f27bc0e53790c to your computer and use it in GitHub Desktop.
Save selfup/b7f908220274f2f36b1f27bc0e53790c to your computer and use it in GitHub Desktop.
Rust code shared from the playground #1
#[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 = State::new();
state.add_user("hello", "world");
let first_user: Option<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