Skip to content

Instantly share code, notes, and snippets.

@quephird
Last active February 7, 2021 06:44
Show Gist options
  • Save quephird/4e6e854b8f55c1d088cf4ffc523bb306 to your computer and use it in GitHub Desktop.
Save quephird/4e6e854b8f55c1d088cf4ffc523bb306 to your computer and use it in GitHub Desktop.
use std::io::stdin;
fn what_is_your_name() -> String {
println!("Hello! What's your name?");
let mut your_name = String::new();
stdin()
.read_line(&mut your_name)
.expect("You forgot to enter something!!!");
your_name
.trim()
.to_lowercase()
}
#[derive(Debug)]
enum VisitorAction {
Accept,
AcceptWithNote { note: String },
Refuse,
Probation,
}
#[derive(Debug)]
struct Visitor {
name: String,
action: VisitorAction,
age: i8,
}
impl Visitor {
fn new(name: &str, action: VisitorAction, age: i8) -> Self {
Self {
name: name.to_lowercase(),
action,
age
}
}
fn greet(&self) {
match &self.action {
VisitorAction::Accept => println!("Welcome to the treehouse, {}!", self.name),
VisitorAction::AcceptWithNote { note} => {
println!("{}", note);
if self.age < 21 {
println!("Do not serve alcohol to {}.", self.name);
}
}
VisitorAction::Probation => println!("{} is now a probationary member", self.name),
VisitorAction::Refuse => println!("Do not let {} in!!!", self.name),
}
}
}
fn find_visitor<'a>(name: &String, visitor_list: &'a Vec<Visitor>) -> Option<&'a Visitor> {
let maybe_visitor = visitor_list
.iter()
.find(|visitor| &visitor.name == name);
maybe_visitor
}
fn main() {
let mut visitor_list = vec![
Visitor::new("bert", VisitorAction::Accept, 45),
Visitor::new("steve", VisitorAction::AcceptWithNote {
note: String::from("Lactose-free milk is in the fridge.")
}, 15),
Visitor::new("fred", VisitorAction::Refuse, 30),
];
loop {
let name = what_is_your_name();
let maybe_visitor = find_visitor(&name, &visitor_list);
match maybe_visitor {
Some(visitor) => visitor.greet(),
None => {
if !name.is_empty() {
println!("{} is not on the list; adding new visitor!", name);
visitor_list.push(Visitor::new(&name, VisitorAction::Probation, 0));
} else {
println!("Goodbye!!!");
break;
}
}
}
}
println!("The final visitor list is:");
println!("{:#?}", visitor_list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment