DEV Community

Zhangwuji
Zhangwuji

Posted on • Updated on

rust lifeCycle

what is lifeCycle?

let a = String::from("ss");
let b;

{
  let c=String::from("test");
  b=&c;

}

print!("{}",b);
Enter fullscreen mode Exit fullscreen mode

&c will not live long enough;
you can solve this problem

    let mut b;

    {
        let c=String::from("test");
        b=&c;

    };
    let c2=String::from("test");
    b=&c2;
    print!("{}",b);
Enter fullscreen mode Exit fullscreen mode

because &c will not be given the control' itself to b; so &c will be destroied; b now is null;if this situation in other language, will throw null pointer error

    let mut b;

    {
        let c=String::from("testfffffffffgggg");
        // let g=Box::new(c);
        b=c;

    };

    print!("{}",b);
Enter fullscreen mode Exit fullscreen mode

now the control of c is given to b; the memory of c in head will not be destroied。

1-------------

fn test(&'a a,&'b b) -> &'a {
   retun b
}

Enter fullscreen mode Exit fullscreen mode

&'a &'b indicate different lifecycle

2-------------------

fn test2(&a a) -> &a{

}
Enter fullscreen mode Exit fullscreen mode

&a equal &'a a if the parameter only have one. this 'a could be omited

3---------------------------

pub struct NewArticle<T> {
    pub headline: String,
    pub content: String,
    pub location: T,
}

impl<T> NewArticle <T> {
    fn summarize(&self,ff:T) -> String {
        //   let content= self.content;
        //   return  content;
        return format!("{}", self.content);
    }


}
Enter fullscreen mode Exit fullscreen mode

&self euqal &'a self

how to use life cycle in Gernerics?

pub struct A <'a>{
    name:&'a 


};
Enter fullscreen mode Exit fullscreen mode
  struct A<'a, T> {
        a: &'a T,
        b: &'a T,
    };
    impl<'a, T> A<'a, T> {
        fn new(one: &'a T, two: &'a T) -> Self {
            A { a: one, b: two }
        }

        fn first(self) -> &'a T {
            self.a
        }

        fn update(self){
            // self.a.push
        }
    }

    let b = A::new(&[1, 23], &[1, 23]);
let c = A::new(&1, &2);
    println!("{:#?}",b.first());
Enter fullscreen mode Exit fullscreen mode

1 is i32 type. it staies in stack, &1 is reference of i32. it also staies in stack。

Top comments (0)