gpt4 book ai didi

rust - 未命名值的范围是什么?

转载 作者:行者123 更新时间:2023-11-29 08:32:16 24 4
gpt4 key购买 nike

未命名的值何时超出范围,何时删除该值?

我正在寻找基于 official docs 的答案,并非基于实验。

示例 1:

f(foo().bar());

示例 2:

match foo().bar() {
// ...
}

如果 barfn bar(self) -> ... 它获得传递值的所有权,并且它像往常一样被删除,但是如果 bar 借用,即 fn bar(&self) -> ...? bar 的结果是否取决于 &self 的生命周期是否重要?

也就是说,foo 可能会返回一个 MutexGuard;重要的是要知道守卫何时被丢弃(并且互斥体被解锁)。

实验方法表明,未命名值在创建它的语句“完成”后被删除;强制“提前”删除 let 语句是必需的。

Playground

#[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");
}

打印:

--- scope test start
foo()
value: ()
Foo::drop()
--- end
--- scope test start
foo()
value: ()
Foo::drop()
--- end
--- scope test start
foo()
Foo::drop()
value: ()
--- end

最佳答案

来自 the reference :

When using an rvalue in most lvalue contexts, a temporary unnamedlvalue is created and used instead, if not promoted to 'static.Promotion of an rvalue expression to a 'static slot occurs when theexpression could be written in a constant, borrowed, and dereferencingthat borrow where the expression was the originally written, withoutchanging the runtime behavior. That is, the promoted expression can beevaluated at compile-time and the resulting value does not containinterior mutability or destructors (these properties are determinedbased on the value where possible, e.g. &None always has the type&'static Option<_>, as it contains nothing disallowed). Otherwise, thelifetime of temporary values is typically

  • the innermost enclosing statement; the tail expression of a block isconsidered part of the statement that encloses the block, or

  • thecondition expression or the loop conditional expression if thetemporary is created in the condition expression of an if or anif/else or in the loop conditional expression of a while expression.

When a temporary rvalue is being created that is assigned into a letdeclaration, however, the temporary is created with the lifetime ofthe enclosing block instead, as using the enclosing statement (the letdeclaration) would be a guaranteed error (since a pointer to thetemporary would be stored into a variable, but the temporary would befreed before the variable could be used). The compiler uses simplesyntactic rules to decide which values are being assigned into a letbinding, and therefore deserve a longer temporary lifetime.

引用文献中有这些规则的示例。

关于rust - 未命名值的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439534/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com