main.rs (1611B)
1 fn main() { 2 let mut s = String::from("why hello there"); 3 s.push_str(" insect!"); 4 println!("{}", s); 5 6 let x = 5; 7 just_copies(x); 8 let y = x; 9 println!("{}", y); 10 11 let mut s1 = String::from("maggot!"); 12 s1 = takes_and_returns(s1); 13 let mut s2 = s1.clone(); 14 println!("s1={}, s2={}", s1, s2); 15 takes_ownership(s1); 16 17 println!("s2.len = {}", get_length(&s2)); 18 println!("{}", s2); 19 20 mut_ref(&mut s2); 21 println!("{}", s2); 22 23 println!("first word={}", first_word(&s2)); 24 println!("3rd word={}", n_word(3, &s2)); 25 } 26 27 fn takes_ownership(s: String) { 28 println!("You're Mine Now, {}", s); 29 } 30 31 fn just_copies(x: u32) { 32 println!("scalars just get copied into the new scope: {}", x); 33 } 34 35 fn takes_and_returns(mut s: String) -> String { 36 println!("You're Mine For Now, {}", s); 37 s.push_str(" I will throw you into the sun!"); 38 s 39 } 40 41 fn get_length(s: &String) -> usize { 42 s.len() 43 } 44 45 fn mut_ref(s: &mut String) { 46 s.push_str(" Scum!"); 47 } 48 49 /* 50 fn dangler() -> &String { 51 let s = String::from("Spooky Ghost!"); 52 &s 53 } 54 */ 55 56 fn first_word(s: &str) -> &str { 57 let bytes = s.as_bytes(); 58 59 for (i, &item) in bytes.iter().enumerate() { 60 if item == b' ' { 61 return &s[..i]; 62 } 63 } 64 65 s 66 } 67 68 fn n_word(n: u32, s: &String) -> &str { 69 let bytes = s.as_bytes(); 70 let mut j = 0; 71 let mut start = 0; 72 73 for (i, &item) in bytes.iter().enumerate() { 74 if item == b' ' { 75 j += 1; 76 if j == n { 77 return &s[start..i]; 78 } 79 start = i; 80 } 81 } 82 83 s 84 }