Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ownership + lifetime example
- // struct that contains a string slice.
- // a string slice is a reference to a string or a part of a string
- #[derive(Debug)]
- struct Foo<'a> {
- // inner uses the same explicit lifetime as the struct which means that
- // the reference needs to be valida at least as long the struct lives
- inner: &'a str
- }
- impl<'a> Foo<'a> {
- // optional "constructor function"
- pub fn new(s: &'a str) -> Self {
- Foo {
- inner: s
- }
- }
- }
- // this function does nothing useful but taking the ownership of a string
- fn take_ownership(s: String) {
- let _ = s.as_bytes();
- }
- fn main() {
- // string
- let s = String::from("some string");
- // instantiate Foo with a reference to s
- let f = Foo::new(&s);
- // this function takes ownership over s
- // after the function finishes s is dropped because it is not longer
- //owned by any scope
- take_ownership(s);
- // our struct is still alive because it is used in this println statement
- // this code will not compile because the reference to s which is stored in our
- // struct has to be valid as long the struct exists due to the explicit lifetime.
- println!("{:?}", f);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement