When do unnamed values go out of scope, when is the value dropped?
I'm looking for an answer based on official docs, not based on experiments.
Example 1:
f(foo().bar());
Example 2:
match foo().bar() {
// ...
}
If bar
is fn bar(self) -> ...
it takes ownership of the passed value, and it is dropped as usual, but what happens if bar
borrows, i.e. fn bar(&self) -> ...
? Does it matter whether the result of bar
depends on the lifetime of &self
?
That is, foo
could be returning a MutexGuard
; it is essential to know when the guard is dropped (and the mutex is unlocked).
The experimental method shows that the unnamed value is dropped after the statement it is created in is "finished"; to force the "early" drop a let
statement is required.
#[derive(Debug)]
pub struct Foo;
pub fn foo() -> Foo {
println!("foo()");
Foo
}
impl Foo {
pub fn bar(&self) {
}
}
impl Drop for Foo {
fn drop(&mut self) {
println!("Foo::drop()");
}
}
fn main() {
println!("--- scope test start");
println!("value: {:?}", foo().bar());
println!("--- end");
println!("--- scope test start");
match foo().bar() {
v => println!("value: {:?}", v),
}
println!("--- end");
println!("--- scope test start");
let v = foo().bar();
println!("value: {:?}", v);
println!("--- end");
}
prints:
--- scope test start
foo()
value: ()
Foo::drop()
--- end
--- scope test start
foo()
value: ()
Foo::drop()
--- end
--- scope test start
foo()
Foo::drop()
value: ()
--- end