use std::cmp::Ordering;
use std::collections::HashMap;
use std::env::args;
use std::fmt::{format, Debug, Display};
use std::fs::File;
use std::{env, fs, io, process, thread};
use std::error::Error;
use std::io::ErrorKind;
use std::pin::pin;
use std::str::Matches;
use std::time::Duration;
use rand::Rng;
use blue_sky::{run, search, Config};
fn main() {
iter();
}
fn iter() {
let vec = vec![1, 2, 3, 4];
let iter = vec.iter();
for item in iter {
println!("{}", item);
}
let vec1 = vec![1, 2, 3, 4];
let iter1 = vec1.iter();
let new_vec:Vec<i32> = iter1.map(|x| x + 1).collect();
for i in new_vec {
println!("{}", i);
}
}
struct Cacher<T>
where
T: Fn(u32) -> u32, {
calculation: T, value: Option<u32>, }
impl<T> Cacher<T>
where
T: Fn(u32) -> u32,
{
fn new(calculation: T) -> Cacher<T> {
Cacher { calculation, value: None }
}
fn value(&mut self, arg: u32) -> u32 {
match self.value {
Some(v) => v,
None => {
let v = (self.calculation)(arg);
self.value = Some(v);
v
}
}
}
}
fn excise_plan() {
let simulated_user_specified_value = 10;
let simulated_random_number = 7;
generate_workout(
simulated_user_specified_value,
simulated_random_number,
);
}
fn generate_workout(intensity: u32, random_number: u32) {
let expensive_closure = |num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};
let mut cacher = Cacher::new(expensive_closure);
if intensity < 25 {
println!(
"Today, do {} pushups!",
cacher.value(intensity));
println!(
"Next, do {} situps!",
cacher.value(intensity)
);
} else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
} else {
println!(
"Today, run for {} minutes!",
cacher.value(intensity)
);
}
}
}
fn mini_grep() {
let case_sensitive = env::var("CASE_INSENSITIVE").is_err();
let args: Vec<String> = args().collect();
let config = Config::new(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {}", err);
process::exit(1);
});
if let Err(e) = run(&config) {
println!("{}", e);
process::exit(1);
}
}
#[cfg(test)]
mod tests {
#[test]
fn unit_test() {
assert_eq!(2 + 2, 3, "这里失败了....");
}
#[test]
#[should_panic]
fn valid_val() {}
}
fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
where
T: Display,
{
println!("Announcement! {}", ann);
if x.len() > y.len() {
x
} else {
y
}
}
fn static_lifecycle() {
let s: &'static str = "I have a static lifetime.";
}
fn test_important_excerpt() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.')
.next()
.expect("Could not find a '.'");
let i = ImportantExcerpt { part: first_sentence };
}
struct ImportantExcerpt<'a> {
part: &'a str,
}
fn longest_test() {
let str1 = String::from("abcd");
let str2 = "xyz";
let r = longest(str1.as_str(), &str2);
println!("{}", r);
}
fn longest<'a>(str1: &'a str, str2: &'a str) -> &'a str {
if str1.len() > str2.len() {
str1
} else {
str2
}
}
fn longest_1<'a>(x: &'a str, y: &str) -> &'a str {
x
}
fn lifecycle_null_ref() {
{
let r = 10; { let x = 5; } println!("r: {}", r); } }
fn trait_test() {
let article = NewsArticle { headline: String::from("xxx"), location: String::from("xxx"), author: String::from("xxx"), content: String::from("xxx") };
println!("{}", article.summarize());
article.default();
trait_as_params(&article);
notify(&article)
}
fn returns_summarizable() -> impl Summary {
NewsArticle { headline: String::from("xxx"), location: String::from("xxx"), author: String::from("xxx"), content: String::from("xxx") }
}
fn some_function<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 {
2
}
fn some_function_simple<T, U>(t: T, u: U) -> i32
where
T: Display + Clone,
U: Clone + Debug,
{
2
}
pub fn notify_advance<T: Summary + SummaryAdvance>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
fn trait_as_params_advanced(summary: &(impl Summary + SummaryAdvance)) {
println!("{:#?}", summary.summarize());
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
fn trait_as_params(summary: &impl Summary) {
println!("{:#?}", summary.summarize());
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
pub trait Summary {
fn default(&self) -> String {
String::from("(Read more...)")
}
fn summarize(&self) -> String;
}
pub trait SummaryAdvance {
fn advanced(&self) -> String;
}
struct PointPosition<T> {
x: T,
y: T,
}
enum PointType<T> {
Some(T),
None,
}
enum Result1<T, E> {
Ok(PointPosition<T>),
Err(E),
}
fn call_generic_type() {
let arr = [1, 2, 3];
println!("aaaaaa {}", generic_type(&arr));
}
fn generic_type<T: std::cmp::PartialOrd + Copy>(arr: &[T]) -> T
{
let mut largest = arr[0];
for &item in arr.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn panic() {
let f = File::open("/Users/qumingxing/Downloads/hello.txt");
let f = match f {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("/Users/qumingxing/Downloads/hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("create file failed!{}", e)
},
other_error => panic!("open file failed!")
}
};
}
fn hashmap() {
let mut map = HashMap::new();
map.insert(1, 2);
map.insert(2, 3);
let v = map.get(&1);
println!("{}", v.expect("v not found"));
for (k, v) in &map {
println!("{} {}", k, v);
}
}
fn vector() {
let vec: Vec<i32> = Vec::new();
let mut vec1 = vec![1, 2, 3];
vec1.push(10);
let v = &vec1[1];
println!("vec1: {:?}", v);
match vec1.get(1) {
Some(third) => println!("vec1: {:?}", third),
None => println!("vec1 is empty")
}
for i in &mut vec1 {
*i += 10;
println!("{}", i);
}
let f1 = vec1.get(100);
println!("{:?}", f1); }
fn let_if_test() {
let x = Some(8);
if let Some(3) = x {
println!("====");
}
}
fn option_test_v2() {
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
Some(i) => Some(i + 1),
None => None
}
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Dime => 2,
Coin::Quarter(state) => {
println!("{:#?}", state);
3
}
Coin::Nickel => 4
}
}
#[derive(Debug)] enum State {
Alabama,
Alaska,
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(State),
}
fn option_test() {
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;
}
fn enum_test() {
let v4 = IpAddrKind::V4(127, 0, 0, 1);
let v6 = IpAddrKind::V6(String::from("::1"));
v6.check();
}
enum IpAddrKind {
V4(u8, u8, u8, u8), V6(String),
}
impl IpAddrKind {
fn check(&self) {
println!("check...");
}
}
fn related_function() {
let phone = Phone::new(String::from("xx"), String::from("xx"));
println!("{:#?}", phone)
}
#[derive(Debug)]
struct Phone {
color: String,
shape: String,
}
impl Phone {
fn new(color: String, shape: String) -> Phone {
Phone { color, shape }
}
}
fn tangle_area_test() {
let rectangle = Rectangle { width: 30, height: 30 };
println!("area:{}", tangle_area(&rectangle));
println!("{}>>", rectangle.area());
}
fn tangle_area(rectangle: &Rectangle) -> u32 {
println!("{:#?}", rectangle);
rectangle.width * rectangle.height
}
#[derive(Debug)] struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
struct Car;
struct Laptop(String, u8);
fn tuple_struct() {
let color = Color(255, 255, 255);
}
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn build_user(active: bool, username: String) -> User {
User { active, username, email: String::from(""), sign_in_count: 11 }
}
fn struct_define() {
let mut user = User { active: true, username: String::from("John"), email: String::from("John.qq.com"), sign_in_count: 12 };
user.username = String::from("jack");
println!("{}", user.sign_in_count);
let user1 = User { active: false, ..user }; println!("{}", user1.active);
}
struct User {
active: bool,
username: String, email: String,
sign_in_count: i32,
}
fn slice_simple() {
let s = String::from("Hello, world!");
let hello = &s[0..5];
let world = &s[6..11];
let slice = &s[3..];
let slice = &s[..3];
let slice = &s[..];
let str = "Hello, world!";
println!("{}", String::from(&str[0..3]));
}
fn slice(s: &String) -> i32 {
let byt = s.as_bytes();
for (i, &item) in byt.iter().enumerate() {
if item == b'o' {
return i as i32;
}
}
byt.len() as i32
}
fn ownership() {
let s = String::from("hello");
take_ownership_str(s);
let x = 10;
take_ownership_int(x);
println!("{}", x);
let mut z = String::from("hello");
take_ownership_borrow(&z);
z.push_str(", world");
println!("{}", z);
let mut h = String::from("hello");
take_ownership_borrow_success(&mut h);
println!("{}", h);
let mut k = String::from("hello");
let k1 = &mut k;
let k2 = &mut k;
println!("{}", k2);
}
fn take_ownership_str(s: String) {
println!("{}", s);
}
fn take_ownership_borrow(s: &String) {
println!("{}", s);
}
fn take_ownership_borrow_success(s: &mut String) {
println!("{}", s);
s.push_str(", world");
}
fn take_ownership_int(i: i32) {
println!("{}", i);
}
fn scope() {
{
let s = "hello"; println!("{}", s); }
}
fn variable_copy() {
let x = 1;
let y = x;
println!("the value of y is : {}", y);
let str1 = String::from("hello");
let str2 = str1;
println!("the value of str2 is : {}", str2);
let str3 = String::from("hello3");
let str4 = str3.clone();
println!("the value of str3 is : {}", str3);
println!("the value of str4 is : {}", str4);
}
fn string_type() {
let str: &str = "hello1";
println!("{}", str);
let str3: &str = &String::from("hello2");
println!("{}", str3);
let str1 = String::from("hello3");
println!("{}", str1);
let mut str4 = String::from("hello4");
str4.push_str(" world!");
println!("{}", str4);
let str5 = format!("{}-{}", str1, str4);
println!("{}", str5);
}
fn foreach() {
let mut count = 0;
loop {
println!("loop");
count += 1;
if count == 5 {
break;
}
}
let result: &str = loop {
if count == 5 {
break "success";
}
};
println!("{}", result);
while count < 10 {
println!("{}", count);
count += 1;
}
let arr = [1, 2, 3, 4, 5];
for x in arr {
println!("{}", x)
}
for x in (0..10).rev() {
println!("{}", x);
}
}
fn condition_express(count: i32) {
if count == 10 {
println!("condition express");
} else if count != 11 {
println!("condition not");
} else {
println!("condition not");
}
let condition: i32 = if count == 12 {
5
} else { 6 };
}
fn return_express_function() -> i32 {
let x: i32 = 1;
x + 2
}
fn other_function(x: i32) {
println!("This is the other function-snake case!{}", x);
let x = {
let y = 10;
y + 1;
};
}
fn data_type() {
let v: u32 = "9".parse().expect("Not valid");
println!("{}", v);
let i8: i8 = 1;
let u8: u8 = 1;
let i16: i16 = 2;
let u16: u16 = 2;
let i32: i32 = 3;
let u32: u32 = 3;
let i64: i64 = 4;
let u64: u64 = 5;
let byt = b'A';
let f32: f32 = 1.0;
let f64 = 2.0;
let flag: bool = true;
let ch: char = 'A';
let tup_vals: (i32, u64, f32) = (-1, 12, 6.9);
println!("{}, {}, {}", tup_vals.0, tup_vals.1, tup_vals.2);
let (x, y, z) = tup_vals;
println!("{} {} {}", x, y, z);
let arr = [1, 2, 3, 4, 5];
let arr_other: [i32; 3] = [1, 2, 3];
let arr_zero = [0; 3];
}
fn variables() {
let x = 5;
println!("The value of x is: {}", x);
let mut y = 5;
println!("The value of y is: {}", y);
y = 6;
println!("The value of y is: {}", y);
const PI: f64 = 3.14;
println!("The value of PI is: {}", PI);
let z = 6;
let z = z + 1;
println!("The value of z is: {}", z);
let spaces = " ";
let spaces = spaces.len();
println!("The value of spaces is: {}", spaces);
}
fn guess() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..11); loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line.");
let guess: u32 = match guess.trim().parse()
{
Ok(num) => num,
Err(_) => continue
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}