rustbook

Toy programs and snippets for The Rust Programming Language book
Log | Files | Refs

main.rs (1389B)


      1 //This struct can only exist within the lifetime of 'part'
      2 struct ImportantExcerpt<'a> {
      3     part: &'a str,
      4 }
      5 
      6 impl<'a> ImportantExcerpt<'a> {
      7     fn level(&self) -> i32 {
      8         3
      9     }
     10 
     11     fn announce(&self, announcement: &str) -> &str {
     12         println!("Attention please: {}", announcement);
     13         self.part
     14     }
     15 }
     16 
     17 fn longest<'a>(s1: &'a str, s2: &'a str) -> &'a str {
     18     if s1.len() > s2.len() {
     19         s1
     20     } else {
     21         s2
     22     }
     23 }
     24 
     25 //Compiler can infer lifetime here, doesn't require explicit definition
     26 fn first_word(s: &str) -> &str {
     27     let bytes = s.as_bytes();
     28 
     29     for (i, &item) in bytes.iter().enumerate() {
     30         if item == b' ' {
     31             return &s[0..i];
     32         }
     33     }
     34     &s[..]
     35 }
     36 
     37 fn main() {
     38     let string1 = String::from("abcd");
     39     {
     40         let string2 = "xyz";
     41         let result = longest(string1.as_str(), string2);
     42         println!("longest = {}", result);
     43     }
     44 //      Complier error, lifetime is out of scope
     45 //        println!("longest = {}", result);
     46 
     47     let passage = String::from(
     48     "It was the best of times. It was the worst of times."
     49     );
     50 
     51     let first = passage.split('.').next().expect("Failed to parse");
     52     let i = ImportantExcerpt {
     53         part: first,
     54     };
     55 
     56     let s: &'static str = "static gives global lifetime";
     57 
     58 /*
     59     let r;
     60 
     61     {
     62         let x = 5;
     63         r = &x;
     64     }
     65 
     66     println!("r: {}", r);
     67 */
     68 }