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?
Asked
Active
Viewed 556 times
0
-
Please post the code where you tried this and it didn't work. If you didn't try any code, why do you think it might not be possible? – Shepmaster Dec 27 '14 at 15:56
-
My original description was not good at describing the problem. This really should not need any code example and I think it is a reasonable question (post-update). – Dec 29 '14 at 23:29
-
Can you explain more about what you mean by "scope"? I still believe that some code examples (even pseudocode) would help us understand what you want to know. As far as I can tell, the answer to your question is "it depends on what called it" (assuming that you mean *the return value of a function*). – Shepmaster Dec 29 '14 at 23:46
-
For example when you have a struct that implements the Drop trait. If the value of that type is returned from a function, does drop() get called when leaving from that function or later? – Dec 31 '14 at 03:06
2 Answers
1
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);
}

nimrodm
- 23,081
- 7
- 58
- 59
1
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 :)