How to do it...

  1. Create a Rust project to work on during this chapter with cargo new chapter_five.
  2. Navigate into the newly created chapter_five folder. For the rest of this chapter, we will assume that your command line is currently in this directory.
  3. Inside the src folder, create a new folder called bin.
  4. Delete the generated lib.rs file, as we are not creating a library.
  5. Open the Cargo.toml file that was generated earlier for you.

  6. Under [dependencies], add the following lines:
lazy_static = "1.0"
regex = "0.2"

If you want, you can go to the crates.io web pages for lazy_static (https://crates.io/crates/lazy_static) and regex (https://crates.io/crates/regex) to check for the newest version and use that one instead.

  1. In the src/bin folder, create a file called lazy_static.rs
  2. Add the following code and run it with cargo run --bin lazy_static:
1    #[macro_use] 
2 extern crate lazy_static;
3 extern crate regex;
4
5 use regex::Regex;
6 use std::collections::HashMap;
7 use std::sync::RwLock;
8
9 // Global immutable static
10 lazy_static! {
11 static ref CURRENCIES: HashMap<&'static str, &'static str> =
{
12 let mut m = HashMap::new();
13 m.insert("EUR", "Euro");
14 m.insert("USD", "U.S. Dollar");
15 m.insert("CHF", "Swiss Francs");
16 m
17 };
18 }
19
20 // Global mutable static
21 lazy_static! {
22 static ref CLIENTS: RwLock<Vec<String>> =
RwLock::new(Vec::new());
23 }
24
25 // Local static
26 fn extract_day(date: &str) -> Option<&str> {
27 // lazy static objects are perfect for
28 // compiling regexes only once
29 lazy_static! {
30 static ref RE: Regex =
31 Regex::new(r"(d{2}).(d{2}).(d{4})")
32 .expect("Failed to create regex");
33 }
34 RE.captures(date)
35 .and_then(|cap| cap.get(1).map(|day| day.as_str()))
36 }
37
38 fn main() {
39 // The first access to CURRENCIES initializes it
40 let usd = CURRENCIES.get("USD");
41 if let Some(usd) = usd {
42 println!("USD stands for {}", usd);
43 }
44
45 // All accesses will now refer to the same,
46 // already constructed object
47 if let Some(chf) = CURRENCIES.get("CHF") {
48 println!("CHF stands for {}", chf);
49 }
50
51 // Mutable the global static
52 CLIENTS
53 .write()
54 .expect("Failed to unlock clients for writing")
55 .push("192.168.0.1".to_string());
56
57 // Get an immutable reference to the global static
58 let clients = CLIENTS
59 .read()
60 .expect("Failed to unlock clients for reading");
61 let first_client = clients.get(0).expect("CLIENTS is
empty");
62 println!("The first client is: {}", first_client);
63
64 let date = "12.01.2018";
65 // The static object is nicely hidden inside
66 // the definition of extract_day()
67 if let Some(day) = extract_day(date) {
68 println!("The date "{}" contains the day "{}"", date,
day);
69 }
70 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.98.148