what is lifeCycle?
let a = String::from("ss");
let b;
{
let c=String::from("test");
b=&c;
}
print!("{}",b);
&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);
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);
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
}
&'a &'b indicate different lifecycle
2-------------------
fn test2(&a a) -> &a{
}
&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);
}
}
&self euqal &'a self
how to use life cycle in Gernerics?
pub struct A <'a>{
name:&'a
};
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());
1 is i32 type. it staies in stack, &1 is reference of i32. it also staies in stack。
Top comments (0)