p_rust 0.1.0

My rust practice
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
use std::collections::HashMap;
use p_rust::customer::eat_at_restaurant;
use crate::garden::vegetables::{Asparagus, AsparagusType};

mod garden;

fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

fn first_word2(s: &str) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}

// fn dangle() -> &String { // dangle returns a reference to a String
//     let s = String::from("hello"); // s is a new String
//     &s // we return a reference to the String, s
// } // Here, s goes out of scope, and is dropped. Its memory goes away. // Danger!

fn no_dangle() -> String {
    let s = String::from("hello");
    s
}

fn another_function(x: i32) {
    println!("The value of x is: {}", x);
}

fn print_label_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {}{}", value, unit_label);
}

fn five() -> i32 {
    5
}

fn plus_one(x: i8) -> i8 {
    x + 1
}

fn takes_ownership(some_string: String) { // some_string comes into scope
    println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing memory is freed.

fn makes_copy(some_integer: i32) { // some_integer comes into scope
    println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.

fn gives_ownership() -> String { // gives_ownership will move its return value into the function that calls it
    let some_string = String::from("yours"); // some_string comes into scope
    some_string // some_string is returned and moves out to the calling function
}

// This function takes a String and returns one
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into scope
    a_string // a_string is returned and moves out to the calling function
}

fn calculate_length(s: String) -> (String, usize) {
    let length = s.len(); // len() returns the length of a string
    (s, length)
}

fn calculate_length2(s: &String) -> usize { // s is a reference to a String
    // s.push_str("jsld"); // won't work
    s.len()
} // Here, s goes out of scope. But because it does not have ownership of what it refers to, nothing happens.

fn change_str(some_string: &mut String) {
    some_string.push_str(", world");
}

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);

    const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
    println!("THREE_HOURS_IN_SECONDS: {}", THREE_HOURS_IN_SECONDS);

    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {}", x);
    }

    println!("The value of x is: {}", x);

    let spaces = "   ";
    let spaces = spaces.len();

    println!("Len of spaces is: {}", spaces);

    let guess: u32 = "42".parse().expect("Not a number!");
    println!("guess is: {}", guess);

    let y: u8 = 255;
    println!("y is {}", y);

    let (k, ab) = u8::overflowing_add(254, 3);
    println!("k is: {}, ab: {}", k, ab);

    let k1 = u8::wrapping_add(254, 3);
    println!("k1 is: {}", k1);

    let k2 = u8::saturating_add(254, 3);
    println!("k2 is: {}", k2);

    // let k3 = u8::checked_add(254, 3).expect("overflowed");
    // println!("k3 is: {}", k3);

    let k3: u8 = match u8::checked_add(254, 2) {
        Some(num) => num,
        None => {
            println!("k3 has error");
            0
        }
    };
    println!("k3 is: {}", k3);

    // addition
    let sum = 5 + 10;
    println!("sum: {}", sum);

    // subtraction
    let difference = 95.5 - 4.3;
    println!("difference: {}", difference);

    // multiplication
    let product = 4 * 30;
    println!("product: {}", product);

    // division
    let quotient: f32 = 56.7 / 32.2;
    let floored = 2 / 3; // Results in 0
    println!("quotient: {}, floored: {}", quotient, floored);

    // remainder
    let remainder = 43 % 5;
    println!("remainder: {}", remainder);

    let t = true;
    println!("t: {}", t);

    let f: bool = false; // with explicit type annotation
    println!("f: {}", f);

    let c = 'z';
    println!("c: {}", c);

    let z = '';
    println!("z: {}", z);

    let heart_eyed_cat = '😻';
    println!("heart_eyed_cat: {}", heart_eyed_cat);

    let tup: (u16, f32, u8) = (500, 6.4, 1);
    let (x, y, z) = tup;
    println!("x: {}, y: {}, z: {}", x, y, z);
    println!("tup: {:?}", tup);
    println!("x: {}", tup.0);

    let quotient = 56.7 / 32.2;
    println!("quotient: {}", quotient);

    let floored = 2 / 3;
    println!("floored: {}", floored);

    let mut arr = [1, 2, 3, 4, 5];
    println!("arr[2]: {}", arr[2]);
    arr[2] = 6;
    println!("mutated arr[2]: {}", arr[2]);

    // let arr2 = [1, 2, 3, 4, 5];
    // println!("Please enter an array index.");
    //
    // let mut index = String::new();
    // io::stdin()
    //     .read_line(&mut index)
    //     .expect("Failed to read line");
    //
    // let index: usize = index.trim()
    //     .parse()
    //     .expect("Index entered was not a number");
    //
    // let element = arr2[index];
    // println!("The value of the element at index {} is: {}", index, element);

    println!("Hello world!");
    another_function(5);
    print_label_measurement(5, 'h');

    let y = {
        let x = 3;
        x + 1
    };
    println!("The value of y is: {}", y);

    let x = five();
    println!("The value of x is: {}", x);

    let x = plus_one(5);
    println!("The value of x is: {}", x);

    let number = 7;
    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }

    if number != 0 {
        println!("number was something other than zero");
    }

    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }

    let condition = true;
    let number = if condition { 5 } else { 6 };
    println!("The value of number is: {}", number);

    // loop {
    //     println!("again!");
    // }

    let mut count = 0;
    'counting_up: loop {
        println!("count = {}", count);
        let mut remaining = 10;

        loop {
            println!("remaining = {}", remaining);
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up;
            }
            remaining -= 1;
        }
        count += 1;
    }
    println!("End count = {}", count);

    let mut counter = 0;
    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };
    println!("The result is {}", result);

    let mut number = 3;
    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }
    println!("LIFTOFF!!!");

    let a = [10, 20, 30, 40, 50];
    let mut index = 0;
    while index < 5 {
        println!("the value is: {}", a[index]);
        index += 1;
    }

    for element in a {
        println!("the value is: {}", element);
    }

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

    { // s is not valid here, it's not yet declared
        let s = "hello"; // s is valid from this point forward
        // do stuff with s
        println!("{}", s);
    } // this scope is now over, and s is no longer valid

    let mut s = String::from("hello");
    s.push_str(", world!");
    println!("{}", s);

    let x = 5;
    let y = x;
    println!("x: {}, y: {}", x, y);

    let s1 = String::from("hello");
    let s2 = String::from(&s1);
    let s3 = s1.clone();
    println!("s1: {}, s2: {}, s3: {}", s1, s2, s3);

    {
        let s = String::from("hello"); // s comes into scope
        takes_ownership(s); // s's value moves into the function and so is no longer valid here

        let x = 5; // x comes into scope
        makes_copy(x); // x would move into the function but i32 is Copy, so it's okay to still use x afterward
        println!("x after makes_copy: {}", x);
    } // Here, x goes out of scope, then s. But because s's value was moved, nothing special happens.

    {
        let s1 = gives_ownership(); // gives_ownership moves its return value into s1
        println!("s1 from gives_ownership: {}", s1);

        let s2 = String::from("hello"); // s2 comes into scope
        let s3 = takes_and_gives_back(s2); // s2 is moved into takes_and_gives_back, which also moves its return value into s3
        println!("s3 from takes_and_gives_back: {}", s3);
    } // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing happens. s1 goes out of scope and is dropped.

    {
        let s1 = String::from("hello");
        let (s2, len) = calculate_length(s1);
        println!("The length of '{}' is {}.", s2, len);
    }

    {
        let s1 = String::from("hello");
        let len = calculate_length2(&s1);
        println!("The length of '{}' is {}.", s1, len);
    }

    {
        let mut s = String::from("hello");
        change_str(&mut s);
        println!("{}", s);
    }

    {
        let mut s = String::from("hello");
        let r1 = &mut s;
        // let r2 = &mut s; // cannot create second mutable reference
        println!("{}", r1);
    }

    {
        let mut s = String::from("hello");
        {
            let r1 = &mut s;
            println!("r1: {}", r1);
        } // r1 goes out of scope here, so we can make a new reference with no problems.

        let r2 = &mut s;
        println!("r2: {}", r2);
    }

    {
        let s = String::from("hello"); // let mut s

        let r1 = &s; // no problem
        let r2 = &s; // no problem
        // let r3 = &mut s; // BIG PROBLEM

        println!("{} and {}", r1, r2);
    }

    {
        let mut s = String::from("hello");

        let r1 = &s; // no problem
        let r2 = &s; // no problem
        println!("{} and {}", r1, r2); // variables r1 and r2 will not be used after this point

        let r3 = &mut s; // no problem
        println!("{}", r3);
    }

    {
        let mut s = no_dangle();
        s.push_str(", world");
        println!("{}", s);
    }

    {
        let mut s = String::from("hello world");
        let word = first_word(&s); // word will get the value 5
        s.clear(); // this empties the String, making it equal to ""

        // word still has the value 5 here, but there's no more string that we could meaningfully use the value 5 with. word is now totally invalid!
        println!("{}", word);
    }

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

        let hello = &s[0..5];
        let mut world = String::from(&s[6..11]);
        world.push_str("!");
        println!("{}, {}", hello, world);
    }

    {
        let s = String::from("hello");
        let slice = &s[0..2];
        println!("slice 1: {}", slice);
        let slice = &s[..2];
        println!("slice 2: {}", slice);
    }

    {
        let s = String::from("hello");
        let len = s.len();
        let slice = &s[3..len];
        println!("slice 1: {}", slice);
        let slice = &s[3..];
        println!("slice 2: {}", slice);
    }

    {
        let s = String::from("hello");
        let len = s.len();
        let slice = &s[0..len];
        println!("slice 1: {}", slice);
        let slice = &s[..];
        println!("slice 2: {}", slice);
    }

    {
        let s = String::from("hello world"); // mut s
        let word = first_word2(&s);
        // s.push_str("!"); // error!
        println!("the first word is: {}", word);
    }

    {
        let mut s = String::from("hello");
        s.push_str(", world");
        s.push_str("!");
        println!("{}", s);
    }

    {
        let my_string = String::from("hello world");

        // `first_word2` works on slices of `String`s, whether partial or whole
        let word = first_word2(&my_string[..6]);
        println!("{}", word);
        let word = first_word2(&my_string[..]);
        println!("{}", word);

        // `first_word2` also works on references to `String`s, which are equivalent to whole slices of `String`s
        let word = first_word2(&my_string);
        println!("{}", word);

        let my_string_literal = "hello world";

        // `first_word2` works on slices of string literals, whether partial or whole
        let word = first_word2(&my_string_literal[..6]);
        println!("{}", word);
        let word = first_word2(&my_string_literal[..]);
        println!("{}", word);

        // Because string literals *are* string slices already, this works too, without the slice syntax!
        let word = first_word2(my_string_literal);
        println!("{}", word);
    }

    {
        let a = [1, 2, 3, 4, 5];
        let slice = &a[1..3];
        assert_eq!(slice, &[2, 3]);
    }

    {
        let vegetable: AsparagusType = garden::test();
        println!("vegetable: {}", vegetable);
        let plant = Asparagus {};
        println!("I'm growing {:?}!", plant);

        eat_at_restaurant();

        let mut map: HashMap<u8, u8> = HashMap::new();
        map.insert(1, 255);
        println!("map: {:?}", map);
    }

    {
        let v: Vec<i32> = Vec::new();
        println!("v: {:?}", v);
        let v = Vec::from([1, 2, 3]);
        println!("v: {:?}", v);

        let mut v = vec![1, 2, 3, 4];
        v.push(5);
        v.push(6);
        v.push(7);
        v.push(8);

        let third = &v[2]; // immutable borrow occurs here
        println!("The third element is {}", third);

        match v.get(100) {
            Some(third) => println!("The third element is {}", third),
            None => println!("There is no third element")
        }

        let first = &v[0]; // immutable borrow occurs here
        // v.push(9); // mutable borrow occurs here
        println!("The first element is: {}", first);

        for i in &mut v {
            *i += 50
        }
        for i in &v {
            println!("{}", i);
        }
        v.push(9); // this is valid
    } // <- v goes out of scope and is freed here

    {
        #[derive(Debug)]
        enum SpreadsheetCell {
            Int(i32),
            Float(f64),
            Text(String),
        }

        let row = vec![
            SpreadsheetCell::Int(3),
            SpreadsheetCell::Text(String::from("blue")),
            SpreadsheetCell::Float(10.12),
        ];

        println!("row: {:#?}", row);
    }

    {
        let data = "initial contents";
        let s = data.to_string();
        println!("s: {}", s);

        // the method also works on a literal directly
        let mut s = "initial contents".to_string();
        println!("s: {}", s);
        s.push_str("dsdf");

        // equivalent to '.to_string()'
        let s = String::from("initial contents");
        println!("s: {}", s);

        println!("{}", "hello".to_string() + ", world");
        println!("{}", format!("hello, {}", "world"));

        let mut s = String::from("foo");
        s.push_str("bar");

        let mut s1 = String::from("foo");
        let s2 = "bar";
        s1.push_str(s2);
        println!("s2 is {}", s2);

        let mut s = String::from("lo");
        s.push('l');
        println!("s: {}", s);

        let s1 = String::from("Hello, ");
        let s2 = String::from("world!");
        let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used
        println!("s3: {}", s3);

        let s1 = String::from("tic");
        let s2 = String::from("tac");
        let s3 = String::from("toe");
        let s = format!("{}-{}-{}", s1, s2, s3);
        println!("s: {}", s);

        let hello = String::from("Hola");
        println!("hello: {}", hello);
        let hello = String::from("Здравствуйте");
        println!("hello: {}", hello);

        let hello = "Здравству123йте";
        let answer = &hello[0..2];
        println!("{}", answer);

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

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

    {
        let mut scores = HashMap::new();
        scores.insert(String::from("Blue"), 10);
        scores.insert(String::from("Yellow"), 50);
        println!("Blue: {}", scores.get("Blue").unwrap());
        println!("Yellow: {}", scores.get("Yellow").unwrap());

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

        let field_name = String::from("Favorite color");
        let field_value = String::from("Blue");

        let mut map = HashMap::new();
        map.insert(&field_name, field_value);
        // field_name and field_value are invalid at this point, try using them and see what compiler error you get!
        println!("field_name: {}, map: {:?}", field_name, map);

        for (key, value) in &scores {
            println!("{}: {}", key, value);
        }

        scores.insert(String::from("Blue"), 10);
        scores.insert(String::from("Blue"), 25);
        println!("scores: {:#?}", scores);

        scores.entry(String::from("Green")).or_insert(55);
        scores.entry(String::from("Blue")).or_insert(55);
        println!("scores: {:#?}", scores);

        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);
    }
}