Rust-- 初级阶段总结

170 阅读1分钟

在学习完rust的基本语法, ownership, borrow, array, vector, enum等概念之后,可以综合上述知识,编写一个小程序:

use std::io::stdin;
#[derive(Debug)]
enum VisitorAction {
    Accept,
    AcceptWithNote { note: String },
    Refuse,
    Probation,
}

#[derive(Debug)]
struct Visitor {
    name: String,
    action: VisitorAction,
    age: u8,
}

impl Visitor {
    fn new(name: &str, action: VisitorAction, age: u8) -> Self {
        Self {
            name: name.to_lowercase(),
            action,
            age,
        }
    }

    fn greet_visitor(&self) {
        match &self.action {
            VisitorAction::Accept => println!("Welcome to the treehouse, {}", self.name),
            VisitorAction::AcceptWithNote { note } => {
                println!("Welcome to the treehouse, {}", self.name);
                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 allow {} in!", self.name),
        }
    }
}

fn what_is_your_name() -> String {
    let mut your_name = String::new();

    stdin()
        .read_line(&mut your_name)
        .expect("Failed to real line!");

    your_name.trim().to_lowercase()
}

fn main() {
    let mut visitor_list: Vec<Visitor> = vec![
        Visitor::new("Bert", VisitorAction::Accept, 45),
        Visitor::new(
            "Steve",
            VisitorAction::AcceptWithNote {
                note: "Lactose-free milk is in the fridge".to_string(),
            },
            15,
        ),
        Visitor::new("Fred", VisitorAction::Refuse, 30),
    ];

    loop {
        println!("Hello, what's your name? (Leave empty and press ENTER to quit)");
        let name = what_is_your_name();

        let known_visitor: Option<&Visitor> =
            visitor_list.iter().find(|visitor| visitor.name == name);

        if let Some(v) = known_visitor {
            v.greet_visitor();
        } else if name.is_empty() {
            break;
        } else {
            println!("Sorry, {} is not on the visitor list.", name);
            visitor_list.push(Visitor::new(&name, VisitorAction::Probation, 0));
        }
    }

    println!("The final list of visitors:");
    println!("{:#?}", visitor_list);
}


参考 [1] hands-on Rust Effective Learning through 2D Game Development and Play