Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. // ownership + lifetime example
  2.  
  3. // struct that contains a string slice.
  4. // a string slice is a reference to a string or a part of a string
  5. #[derive(Debug)]
  6. struct Foo<'a> {
  7. // inner uses the same explicit lifetime as the struct which means that
  8. // the reference needs to be valida at least as long the struct lives
  9. inner: &'a str
  10. }
  11.  
  12. impl<'a> Foo<'a> {
  13. // optional "constructor function"
  14. pub fn new(s: &'a str) -> Self {
  15. Foo {
  16. inner: s
  17. }
  18. }
  19. }
  20.  
  21. // this function does nothing useful but taking the ownership of a string
  22. fn take_ownership(s: String) {
  23. let _ = s.as_bytes();
  24. }
  25.  
  26. fn main() {
  27. // string
  28. let s = String::from("some string");
  29.  
  30. // instantiate Foo with a reference to s
  31. let f = Foo::new(&s);
  32.  
  33. // this function takes ownership over s
  34. // after the function finishes s is dropped because it is not longer
  35. //owned by any scope
  36. take_ownership(s);
  37.  
  38. // our struct is still alive because it is used in this println statement
  39. // this code will not compile because the reference to s which is stored in our
  40. // struct has to be valid as long the struct exists due to the explicit lifetime.
  41. println!("{:?}", f);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement