fust_tutorials 0.1.0

a fast rust tutorials
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use std::fmt::{Display, Debug};
use std::io::{self, ErrorKind, Write, Read};


fn variable_test() {
    // 变量默认不可变
    let x = 5;
    // x = 6;   // 非法
    let x = "hello, world";  // 第一个变量 x, 被隐藏了
    print!("x is {}\n", x);
}

fn typeofdata() {
    // 显式注明变量类型, 不能智能判断
    let guess: u32 = "42".parse().expect("not a number");
    print!("guess is {}\n", guess);
}

fn arra_y() {
    let a = [3; 5];
    let mut index = String::new();

    io::stdin().read_line(&mut index).expect("Failed to read line");

    let index: usize = index.trim().parse().expect("Index extered was not a number");

    let element = a[index];
    println!("value is {}", element)
}

fn add(x: i32, y: i32) -> i32 {
    x + y
}

fn func() {

    let x = add(4, 5);
    println!("4 add 5 is {}", x);
}

fn judge(x: i32) {
    let number = if x > 0 {1} else {0};
    println!("number is {}", number);
}

fn cycle() {
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter >= 10 {
            break counter * 2;  // break 有返回值
        }
    };

    println!("result is {}", result);
}

fn label() {
let mut i = 1;
'counting_up: loop {    // break `counting_up 从该层循环退出
    let mut j =  1;
    loop {
        if i >= 2 {
            break 'counting_up;
        }

        if j > 9 {
            break;
        }

        println!("{} * {} = {}", i, j, i * j);
        j+=1;

    }

    i += 1;
}
}

fn use_while() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");

        number -= 1;
    }
}

fn for_in() {
    let arr = [3;4];

    for (i, e) in arr.iter().enumerate() {
        println!("the {}th element is {}", i, e);
    }

    for number in (1..4).rev() {
        println!("{number}!");
    }
}

fn get_ownership() -> String {
    String::from("yours")
}

fn take_and_back(s: String) -> String {
    s
}

fn ownership() {
    let s1 = get_ownership();
    let s2 = String::from("hello");
    let s3 = take_and_back(s2);

    println!("s1: {}", s1);
    // println!("s2: {}", s2);  // 所有权被转移
    println!("s3: {}", s3);
}

fn reference() {
    let mut s = String::from("hello, ");
    change(&mut s);
    println!("now s is: {}", s);

    let r1 = &mut s;
	// s.push_str("~~");         // 这样也会报错: 不能同时有两个可变引用
    r1.push_str("!");
    println!("r1 is {}", r1);

    s.push_str("~~");
    // println!("r1 is {}", r1);    // r1 被使用,报错
    println!("s is {}", s);   // r1 不再使用, 没问题
}

fn change(s: &mut String) {
    s.push_str("world");
}


fn slice() {
    slice_str();

    slice_num();
}

fn slice_num() {
    let a = [1,2,3,4,5];
    let slice: &[i32] = &a[1..3];

    assert_eq!(slice, &[2,3]);
}

fn slice_str() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world: &str = &s[6..];
    println!("{}, {}", hello, world);

    let first = first_word(&s);
    
    println!("first word is `{}`", first);

}

fn first_word(s: &str) -> &str {    // s &String 隐式转换为 &str
    let bytes = s.as_bytes();

    // 这里的 c 为什么要加 &
    for (i, &c) in bytes.iter().enumerate() {
        if c == b' ' {
            return &s[..i];
        }
    }

    &s[..]
}

#[derive(Debug)]
// or manually `impl Debug for User
struct User {
    active: bool,
    name: String,
    email: String,
}

fn structure() {
    let mut user = User {
        active: true,
        name: String::from("dawson"),
        email: String::from("957360688@qq.com"),    // 不能少任何一个字段, 奇怪
    };
    user.email = String::from("jeedq@qq.com");

    // 如果后面不用了, 可以把 user.email 转移, 如果用,就不能转移
    // let anthor_user = build_user(user.name, user.email);
    // println!("email: {}", user.email)   // 这里使用了, 则不能转移

    println!("email: {}", user.email);   // 使用后不再使用, 可以转移
    let two = build_user(user.name, user.active);

    let three = User {
        name: String::from("nera"),
        ..user  // 展开 user, active 是复制类型, email 还没有被转移
    };

    println!("user: {:?}", two)
}

fn build_user(name: String, active: bool) -> User {
    User { active, name, email:String::from("xxx@qq.com") }  // 变量名和结构体名一样, 简化
}

fn tuple_struct() {
    struct Color(i32, i32, i32);

    let klein_blue = Color(0, 47, 167);

    println!("klein bule is R: {}, G: {}, B: {}", klein_blue.0, klein_blue.1, klein_blue.2);
}


fn method() {
    let rec = Rectangle {
        width: 4,
        height: 5
    };

    println!("area is {}", rec.area());

    println!("new a square.");
    let squ = Rectangle::square(5);
    println!("square's ares is {}", squ.area())
}

fn struct_simple() {
    let rec = Rectangle {
        width: 3,
        height: 4,
    };

    println!("area: {}", area(rec));

    // 这里也是不可用的
    // 因为定义的 Rectangle 这个结构体没有实现 Copy
    // move occurs because `rec` has type `Rectangle`, 
    // which does not implement the `Copy` trait
    // println!("area: {}", rec.height * rec.width);

    let x = 3;
    let y = back(x);

    // 这里则是可用的
    println!("x: {}", x);
}

fn area(rec: Rectangle) -> u32 {
    rec.width * rec.height
}

fn back(x: u32) -> u32 {
    x
}

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

impl Message {
    fn call(&self) -> &str {

    let x = match self {
            Message::Quit => "quit",
            Message::Move{x, y} => "move",
            Message::Write(str) => str,
            _ => "other"
        };

        x
    }
}

fn enumerate() {
    let m = Message::Write(String::from("hello"));
    let str = m.call();
    println!("message call is {}", str);
}

fn if_let() {
    let some_num = Some(2);

    let x = if let Some(i) = some_num {
        i
    } else {    // 相当于 match 中的 _
        0
    };
}

fn module() {
}

fn vector() {
    let mut v = vec![1,2,3];

    let first = &v[0];
    v.push(4);

    // push 改变了 v,所以 first 有可能失效。
    // println!("first element is {}", first);

    let last = v.pop();
    match last {
        Some(i) => println!("last is {}", i),
        None => println!("vector empty"),
    };

    for i in &mut v {
        *i += 50;
    }

    println!("vector now {:?}", v);
}

fn string() {
    let mut s1 = String::from("foo");
    let temp = "bar";

    s1.push_str(temp);
    // 说明 temp 可复制
    println!("temp can use: {}", temp);

    let mut s2 = String::from("lo");
    s2.push('l');

    // + 相当于
    // fn add(self, s: &str) -> String
    // 所以 s1 也不再有效
    let s3 = s1 + &s2;  
    println!("s3: {}", s3);

    let s4 = format!("{}-{}", s2, s3);
    println!("s4: {}", s4);

    let hello = "Здравствуйте".to_string();
    let ans = &hello[0..2]; // 慎用,用可能 panic

    for c in hello.chars() {
        print!("{} ", c);
    }
    println!();

    for b in hello.bytes() {
        print!("{} ", b);
    }
    println!();
}


use std::collections::HashMap;
fn 哈希() {
    let mut scores: HashMap<String, usize> = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    // insert 相同的值,会被覆盖
    scores.entry("Yellow".to_string()).or_insert(50);

    let value = scores.get("Blue");
    for (key, value) in &scores {
        println!("{}: {}", key, value); // 无序打印 unordered map
    }

    let teams = vec![String::from("Blue"), String::from("Yellow")];
    let initial_scores = vec![10, 50];
    let mut score: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect();


    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: {:?}", map);
}


use std::fs::{File, OpenOptions};
use std::thread;
use std::time::Duration;

use fust_tutorials::{Tweet, Summary, Rectangle};
fn error_handle() {
    let file = "hello.txt";

    let mut f = match OpenOptions::new().read(true).write(true).open(file) {
    // let mut f = match File::open(file) {
        Ok(file) => file,
        Err(error) => match error.kind() {
            ErrorKind::NotFound => match File::create(file) {
                Ok(fc) => fc,
                Err(e) => panic!("creat file failed: {}", e),
            }

            other_error => panic!("open file: {}", other_error),
        }
    };

    let text = "hello, world".as_bytes();
    match f.write(text) {
        Ok(num) => println!("write {} bytes to {}", num, file),
        Err(e) => panic!("error write: {}", e)
    };
}

fn error_handle_with_wrap_helper(file: &str) -> Result<String, io::Error> { // 枚举是一个范型, 范型用<>

    // 闭包
    let mut f = File::open("file").unwrap_or_else(|error | {
        if error.kind() == ErrorKind::NotFound {
            File::create(file).expect("Failed to create file")
        } else {
            panic!("Problel opening file: {:?}", error);
        }
    });


    let mut s = String::new();
    // ------------------------------
    // match f.read_to_string(&mut s) {
    //     Ok(num) => {
    //         println!("read {} bytes to buf", num);
    //         Result::Ok(s)
    //     },
    //     Err(e) => Err(e)
    // }
    // 可简写为
    let num = f.read_to_string(&mut s)?;
    // 1. 如果 Result 的值是 Ok,返回 Ok 中的值,程序继续执行。
    // 2. 如果值是 Err,Err 中的值将作为整个函数的返回值,
    // 就好像使用了 return 关键字一样,这样错误值就被传播给了调用者。
    // 上面的 File::open 也可以用?来简化

    println!("read {} bytes to buf", num);
    Ok(s)
    // -----------------------------

}

fn error_handle_with_wrap() {
    let file = "hello.txt";

    let mut s = error_handle_with_wrap_helper(file).unwrap();
    s.push_str("...");
    println!("the {}'s content is:", file);
    println!("{}", s);
}

fn largest<T: std::cmp::PartialOrd + Copy>(list: &[T]) -> T {
    let mut ret: T = list[0];

    for &ele in list {
        if ele > ret {
            ret = ele;
        }
    }

    ret
}

fn generic_type() {
    let numbers = vec![4,6,9,2,4,7];

    let ret = largest(&numbers);
    println!("the largest is {}", ret);
}


fn impl_trait() {
    let tweet = Tweet {
        author: "dawson".to_string(),
        content: "dawson is a good boy".to_string(),
        reply_number: 255,
        can_retweet: false
    };

    notify(&tweet);
}

// trait 作为参数
// fn notify<T: Summary>(tweet: &T) {
fn notify(tweet: &impl Summary) {
    println!("{}", tweet.summarize());
}

fn some_func<T, U>(t: &T, u: &U) -> i32 
    where T: Display + Clone,
          U: Clone + Debug
{
    1
}

// fn lifetime() {
//     let ret;
//     let x = String::from("xxxxxx");
//     {
//         let y = String::from("yyyyyyyyyyyy");
//         // 这里要保证 ret 的引用释放时机在前 (x 和 y 释放早的那个)
//         ret = longest(&x, &y);
//     }

//     println!("the longer str is: {}", ret);
// }

//意味着 ImportantExcerpt 的实例不能比其 part 字段中的引用存在的更久。
struct Excerpt<'a> {
    part: &'a str,
}

fn lifetime() {
    let novel = String::from("Call me Dawson. some years ago...");
    let first_sentence = novel.split('.').next().expect("Cound not find a '.'");
    let excerpt = Excerpt {
        part: first_sentence
    };
}

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}


fn compare<'a, T>(x: &'a str, y: &'a str, conn: T) -> &'a str 
    where T: Display
{
    println!("display: {}", conn);
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

fn simple() {
    let x = String::from("hello, world!");
    let y = String::from("Dawson Jones");
    let conn = "I'm the king of the world";

    println!("the longer: {}", compare(&x, &y, conn));
}

// struct Cacher {
//     // `impl Trait` only allowed in function and inherent method return types, not in type
//     calculation: impl Fn(u32) -> u32,
// }

use std::hash::Hash;
struct Cacher<T, U> 
    where T: Fn(U) -> U, 
          U: Hash + Eq,
{
    calculation: T,
    // value: Option<U>,
    value: HashMap<U, U>,
}

impl<T, U> Cacher<T, U>
    where T: Fn(U) -> U, 
          U: Hash + Eq + Copy,
{
    fn new(calculation: T) -> Self {
        Cacher { calculation, value: HashMap::new() }
    }

    fn get_value(&mut self, arg: U) -> U {
        match self.value.get(&arg) {
            Some(v) => *v,
            None => {
                // 不用括包包起来说明使用了一个实现的方法
                let v= (self.calculation)(arg);
                self.value.insert(arg, v);
                v
            }
        }
    }
}

fn generate_workout(intensity: u32, random_number: u32) {
    let mut expensive_result = Cacher::new(|num| {
        println!("calculating slowly...");
        thread::sleep(Duration::from_secs(2));
        num
    });

    if intensity < 25 {
        println!("Today, do {} pushups!", expensive_result.get_value(intensity));
        println!("Next, do {} situps!", expensive_result.get_value(intensity));
        // println!("Today, do {} pushups!", expensive_result.get_value("hello"));
        // println!("Next, do {} situps!", expensive_result.get_value("hello"));
    } else {
        if random_number == 3 {
            println!("Take a break today! Remember to stay hydrated!");
        } else {
            println!(
                "Today, run for {} minutes!",
                expensive_result.get_value(intensity)
                // expensive_result.get_value("world")
            );
        }
    }
}

fn closure() {
    let simulated_user_specified_value = 10;
    let simulated_random_number = 7;

    println!("----start----");
    generate_workout(simulated_user_specified_value, simulated_random_number);
    println!("----end----");
}

fn iterator() {
    let shoe = vec![6, 7, 8];

    let filter: Vec<i32> = shoe.into_iter().filter(|size| size % 2 == 0).collect();

    for ele in filter.iter() {
        println!("{}", ele);
    }
}

struct Counter {
    start: u32,
    end: u32,
}

fn range(start: u32, end: u32) -> Counter {
    Counter { start, end }
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.start < self.end {
            self.start += 1;
            Some(self.start - 1)
        } else {
            None
        }
    }
}

fn imple_iterator() {
    for ele in range(1, 5) {
        print!("{} ", ele);
    }

    println!();
}


fn main() {
    // 1. 变量使用
    variable_test();

    // // 2. 数据类型
    // typeofdata();
    // arra_y();

    // 3. 函数
    func();

    // 4. 控制流
    judge(-2);
    cycle();
    // label();
    // use_while();
    for_in();

    // 5. 所有权
    ownership();

    // 6. 引用
    reference();
    slice();

    // 7. 结构体
    structure();
    tuple_struct();
    struct_simple();

    // 8. 方法
    method();

    // 9. 枚举
    enumerate();
    if_let();

    // 10. module
    // module();

    // 11. 常用类型
    vector();
    string();
    哈希();

    // 12. 错误处理
    error_handle();
    // error_handle_with_wrap();

    // 13. 范型
    generic_type();
    // 14. trait
    impl_trait();
    // 15. 生命周期 
    lifetime();
    // 16. 例子
    simple();

    // 17. test

    // 18. 闭包
    // closure();

    // 19. 迭代器
    iterator();
    imple_iterator();

    // 20. 文档注释
    fust_tutorials::add_two(5);

}