[Rust] Ownership

Zhentiw發表於2024-04-08

The following code will have borrowing problem

fn print_years(years: Vec<i32>) {
   for year in years.iter() {
      println!("Year: {}", year); 
   }
} // dealloc(years): after function scrop ends, dealloc happen

fn man() {
   let years = vec![1990,1995,2000,2010];
    
    print_years(years); // years got deallocated
    print_years(years); // compile error
}

Reoslve use-after-move compiler error: transfer ownership to caller scope by add return keyword in function.

fn print_years(years: Vec<i32>) -> Vec<i32> {
   for year in years.iter() {
      println!("Year: {}", year); 
   }
    
   return years; // If we add return, Rust will transfer ownership to caller scope
}

fn main() {
   let years = vec![1990,1995,2000,2010];
    
    let years2 = print_years(years);
    let years3 = print_years(years2);
}

.clone() is your friend when you are a beginner :)

fn print_years(years: Vec<i32>) -> Vec<i32> {
   for year in years.iter() {
      println!("Year: {}", year); 
   }
}

fn main() {
   let years = vec![1990,1995,2000,2010];
    
    print_years(years.clone());
    print_years(years);
}

相關文章