Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. fn first_word(a: &str) -> &str {
  2. println!("{}", a);
  3. "hi"
  4. }
  5.  
  6. fn first_word(s: &String) -> &str {
  7. let bytes = s.as_bytes();
  8.  
  9. for (i, &item) in bytes.iter().enumerate() {
  10. if item == b' ' {
  11. return &s[0..i];
  12. }
  13. }
  14.  
  15. &s[..]
  16. }
  17.  
  18. fn main() {
  19. let mut s = String::from("hello world");
  20.  
  21. let word = first_word(&s);
  22.  
  23. s.clear(); // error!
  24.  
  25. println!("the first word is: {}", word);
  26. }
  27.  
  28. // fn main() {
  29. // let mut s = String::from("hello world");
  30.  
  31. // let word = first_word(&s); // word will get the value 5
  32.  
  33. // s.clear(); // this empties the String, making it equal to ""
  34.  
  35. // // word still has the value 5 here, but there's no more string that
  36. // // we could meaningfully use the value 5 with. word is now totally invalid!
  37. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement