fust_tutorials 0.1.0

a fast rust tutorials
Documentation
// mod front_of_house 后使用分号,而不是代码块
// 这将告诉 Rust 在另一个与模块同名的文件中加载模块的内容
mod front_of_house;

pub use front_of_house::hosting;


pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}


// 定义一组行为
pub trait Summary {
    fn summarize_author(&self) -> String;

    // 默认行为, 可以重写
    fn summarize(&self) -> String {
        // 因为不知道谁实现了 trait, 所以不能用 self 的成员
        format!("Read more from {}...", self.summarize_author())
    }
}

struct News {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

pub struct Tweet {
    pub author: String,
    pub content: String,
    pub reply_number: usize,
    pub can_retweet: bool,
}


impl Summary for News {
    fn summarize_author(&self) -> String {
        self.author.to_string()
    }

    // 重写默认实现
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

impl Summary for Tweet {
    fn summarize_author(&self) -> String {
        self.author.to_string()
    }
}

pub struct Rectangle {
    pub width: u32,
    pub height: u32
}

impl Rectangle {
    // 可简写为 &self
    pub fn area(self: &Self) -> u32 {
        self.height * self.height
    }

    pub fn square(size: u32) -> Self {
        Self { width: size, height: size }
    }

    fn can_hold(&self, other: &Self) -> bool {
        self.width > other.width && self.height > other.height
    }
}

mod guess;

#[cfg(test)]
mod tests {
    #[test]
    fn test_add() {
        assert_eq!(2 + 2, 4);
    }

    use super::*;

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };

        let smaller = Rectangle {
            width: 5, 
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }

    fn greeting(name: &str) -> String {
        format!("heelo,{}", name)
    }

    #[test]
    fn contain_name() {
        let result = greeting("dawson");

        assert!(
            result.contains("dawson"),
            "not contain nmae, value was {}",
            result
        );
    }

    use guess::Guess;

    #[test]
    // #[should_panic]    // 都可以
    #[should_panic(expected = "Guess value must be between 1 - 100")]   // 信息是 panic 的字串
    fn greter_than_100() {
        Guess::new(200);

    }

    #[test]
    #[ignore]
    fn it_works() -> Result<(), String> {
        if 2 + 2 == 4 {
            Ok(())
        } else {
            Err(String::from("2 + 2 != 4"))
        }
    }
}

/// Add two to the number given.
/// 
/// # Examples
/// ```
/// let arg = 5;
/// let answer = fust_tutorials::add_two(arg);
/// 
/// assert_eq!(7, answer);
/// 
pub fn add_two(num: i32) -> i32 {
    num + 2
}