use rand::Rng;
use std::cmp::Ordering;
use std::io;
mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn add_one(x: i32) -> i32 {
x + 1
}
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[allow(warnings)]
fn guess_num_game() {
let secret_number = rand::thread_rng().gen_range(0..=100);
println!("guess a num😛");
println!("num is : {}", secret_number);
loop {
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Unable to read row!");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("guess num is : {}", secret_number);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Smaller!"),
Ordering::Greater => println!("Bigger!"),
Ordering::Equal => {
println!("Guess right!");
break;
}
}
}
}
#[allow(warnings)]
mod back_of_house {
pub struct Breakfast {
pub toast: String,
seassonal_fruil: String,
}
impl Breakfast {
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seassonal_fruil: String::from("peaches"),
}
}
}
fn fix_incorrect_order() {
cook_order();
super::serve_order();
crate::serve_order();
}
fn cook_order() {}
}
fn serve_order() {}
pub fn eat_at_restaurant() {
let mut meal = back_of_house::Breakfast::summer("Rye");
meal.toast = String::from("Wheat");
println!("{}", meal.toast);
}
pub trait Summary {
fn summarize(&self) -> String {
format!("(Read more from {}...)\n", self.summarize_author())
}
fn summarize_author(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
fn summarize_author(&self) -> String {
format!("@{}", self.author)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cmp::PartialOrd;
use std::collections::HashMap;
use std::fs::File;
use std::io::{self, ErrorKind, Read};
use std::net::IpAddr;
use std::process::Command;
#[test]
fn string_slice() {
let s = String::from("Hello world");
let word_index = first_world(&s[..]);
let hello = &s[..=4];
let world = &s[6..];
println!("{} {} {}", word_index, hello, world);
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
for i in slice {
println!("{}", i);
}
println!("{}", slice[0]);
println!("{}", slice[1]);
}
fn first_world(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
#[test]
fn test_struct() {
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someone"),
active: true,
sign_in_count: 1,
};
let user2 = User {
email: user1.email,
username: String::from("user2"),
..user1
};
println!(
"{} {} {} {}",
user2.username, user2.email, user2.sign_in_count, user2.active
);
}
#[test]
fn test_rectangele() {
#[derive(Debug)]
struct Rectangle {
width: u32,
length: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.length
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.length > other.length
}
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
length: size,
}
}
}
let s = Rectangle::square(20);
println!("{:#?}", s);
let rect1 = Rectangle {
width: 30,
length: 50,
};
let rect2 = Rectangle {
width: 10,
length: 40,
};
let rect3 = Rectangle {
width: 35,
length: 55,
};
println!("{}", rect1.can_hold(&rect2));
println!("{}", rect1.can_hold(&rect3));
println!("{}", rect1.area());
println!("{:#?}", rect1);
}
#[test]
#[allow(warnings)]
fn test_enum() {
enum IpAddrKind {
V4(u8, u8, u8, u8),
V6(String),
Move { x: i32, y: i32 },
}
let home = IpAddrKind::V4(127, 0, 0, 1);
let loopback = IpAddrKind::V6(String::from("::1"));
route(home);
route(loopback);
fn route(ip_kind: IpAddrKind) {}
}
#[derive(Debug)]
#[allow(warnings)]
enum UsState {
Alabama,
Alaska,
}
#[derive(Debug)]
#[allow(warnings)]
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
#[test]
fn test_enum_match() {
let c = Coin::Quarter(UsState::Alaska);
println!("{}", value_in_cents(c));
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("{:#?}", state);
25
}
}
}
#[test]
fn test_if_let() {
let five = Some(5);
let six = plus_one(five);
assert_eq!(Some(6), six);
let none = plus_one(None);
assert_eq!(None, none);
let v = Some(3u8);
if let Some(a) = v {
println!("{}", a);
} else {
println!("others");
}
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
#[test]
fn test_vec() {
let mut v: Vec<i32> = Vec::new();
for number in 1..=4 {
v.push(number);
println!("{}", number);
}
match v.get(20) {
Some(third) => println!("{}", third),
None => println!("NONE"),
}
let first = &v[0];
println!("{}", first);
}
#[test]
fn test_string() {
let s1 = "😀ni好";
let s2 = ",world".to_string();
let s = format!("{}{}", s1, s2);
for b in s1.bytes() {
println!("{}", b);
}
for b in s1.chars() {
println!("{}", b);
}
let s3 = &s[..9];
println!("{}", s3);
}
#[test]
fn test_hashmap() {
let mut scores = HashMap::new();
scores.insert("Blue".to_string(), 10);
let teams = vec!["Blue".to_string(), "Yellow".to_string()];
let intial_scores = vec![10, 50];
let scores: HashMap<_, _> = teams.iter().zip(intial_scores.iter()).collect();
let team_name = "Blue".to_string();
let score = scores.get(&team_name);
match score {
Some(s) => println!("{}", s),
None => println!("team not exist"),
}
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:#?}", map);
}
#[test]
#[should_panic]
fn test_panic() {
let v = vec![1, 2, 3];
v[99];
println!("finish");
}
#[test]
fn test_error() {
test_read_file();
let s = read_username_from_file();
match s {
Ok(file) => println!("{}", file),
Err(error) => println!("{}", error),
}
let home: IpAddr = "127.0.0.1".parse().unwrap();
println!("{}", home);
}
fn test_read_file() -> File {
let f = File::open("hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Error creating file: {:?}", e),
},
oe => panic!("Error opening file {:?}", oe),
},
};
f
}
fn read_username_from_file() -> Result<String, io::Error> {
let mut s = String::new();
File::open("hello.txt")?.read_to_string(&mut s)?;
Ok(s)
}
#[test]
fn use_guess() {
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess btn 1 and 100, got {}", value);
}
Guess { value }
}
pub fn value(&self) -> i32 {
self.value
}
}
let guess = Guess::new(30);
println!("{}", guess.value);
println!("{}", guess.value());
}
#[test]
fn test_largest() {
let mut number_list = [1, 4, 2, 3];
increase(&mut number_list);
show(&number_list);
let result = largest(&number_list);
println!("{}", result);
for item in number_list.iter() {
print!("{} ", &item);
}
println!();
let char_list = vec!["da", "da", "ads", "easd", "bsa"];
let result = largest(&char_list);
println!("{}", result);
}
fn largest<T: PartialOrd + Clone>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn increase(list: &mut [i32]) {
for item in list.iter_mut() {
*item += 1;
}
}
fn show(list: &[i32]) {
for &item in list.iter() {
print!("{} ", item);
}
}
#[test]
fn test_trait() {
let tweet = Tweet {
username: "horse_ebooks".to_string(),
content: "of course, shuodedaoli".to_string(),
reply: false,
retweet: false,
};
println!("{}", tweet.summarize());
let article = NewsArticle {
headline: "ASDAasdasd".to_string(),
content: "asdsadadsadsadasdasdas".to_string(),
author: "xin".to_string(),
location: "jiangsu".to_string(),
};
print!("{}", article.summarize());
}
#[allow(warnings)]
struct ImportantExcerpt<'a> {
part: &'a str,
}
#[allow(warnings)]
impl<'a> ImportantExcerpt<'a> {
fn level(&self) -> i32 {
3
}
}
#[allow(warnings)]
struct ImportantExcerpt2 {
part: &'static str,
}
#[allow(warnings)]
impl ImportantExcerpt2 {
fn level(&self) -> i32 {
3
}
}
#[allow(warnings)]
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
#[test]
fn iterator_demonstration() {
let v1 = vec![1, 2, 3];
let mut v1_iter = v1.iter();
assert_eq!(v1_iter.next(), Some(&1));
assert_eq!(v1_iter.next(), Some(&2));
assert_eq!(v1_iter.next(), Some(&3));
}
#[test]
fn test_iterator_sum() {
let v1 = vec![1, 2, 3];
let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
println!("{:#?}", v2);
}
#[test]
fn using_other_iterator_trait_methods() {
let sum: u32 = Counter::new()
.zip(Counter::new().skip(1))
.map(|(a, b)| a * b)
.filter(|x| x % 3 == 0)
.sum();
println!("{}", sum);
}
#[test]
fn calling_next_directly() {
let mut counter = Counter::new();
println!("{:?}", counter);
for i in 0..7 {
let n = counter.next();
println!("i{}: {:?}", i, n);
}
}
#[derive(Debug)]
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < 5 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
#[test]
#[allow(warnings)]
fn cmd() {
let output = Command::new("ls")
.output()
.expect("failed to execute command");
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
println!("Command executed successfully. Output:\n{}", stdout);
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
println!("Command failed. Error:\n{}", stderr);
}
}
}