user625070
user625070

Reputation:

What is the scope of the returned value in Rust?

What happens to the data referenced by the variable when it is returned to the caller? When the data is destroyed and possibly Drop trait gets executed?

Upvotes: 0

Views: 609

Answers (2)

user625070
user625070

Reputation:

I didn't understand the life cycle of the data in Rust when I wrote this question. Returning a value causes ownership of the data to move to the variable assigned by the caller. Trivial but I just had started to experiment with the language when I wrote the question :)

Upvotes: 1

nimrodm
nimrodm

Reputation: 23799

Seems like you can (why not?):

use std::io::File;

fn open_file(path: &Path) -> File {
  let file = File::open(path).unwrap() ;
  file
}


fn main() {
  let path = Path::new("hello.txt");
  let mut file = open_file(&path);

  let str =  file.read_to_string().unwrap();
  println!("Contents of {}:\n{}\n", path.display(), str);
}

Upvotes: 1

Related Questions