返回使用StdinLock的结果时,为什么保留对stdin的借用? [英] When returning the outcome of consuming a StdinLock, why was the borrow to stdin retained?

查看:65
本文介绍了返回使用StdinLock的结果时,为什么保留对stdin的借用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供以下功能:

use std::io::{BufRead, stdin};

fn foo() -> usize {
    let stdin = stdin();
    let stdinlock = stdin.lock();
    stdinlock
        .lines()
        .count()
}

这无法编译并出现以下错误:

This fails to compile with the following error:

error: `stdin` does not live long enough
  --> src/main.rs:12:1
   |
7  |     let stdinlock = stdin.lock();
   |                     ----- borrow occurs here
...
11 | }
   | ^ `stdin` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

我发现这很令人惊讶,因为使用锁(通过lines)的结果没有保留对原始源的任何引用.实际上,在返回之前将相同的结果分配给绑定可以正常工作(游乐场).

I find this surprising because the outcome of consuming the lock (via lines) does not retain any references to the original source. In fact, assigning the same outcome to a binding before returning works just fine (Playground).

fn bar() -> usize {
    let stdin = stdin();
    let stdinlock = stdin.lock();
    let r = stdinlock
        .lines()
        .count();
    r
}

这表明立即返回已使用的锁"已导致锁尝试生存的时间比锁定的内容更长,这是一种不寻常的方式.我研究过的所有引用通常都指出声明的顺序很重要,但返回的对象如何影响释放它们的顺序却无关紧要.

This suggests that returning a "consumed lock" immediately has led to the lock attempting to live longer than the locked content, much in an unusual way. All references that I looked into usually point out that the order of declaration matters, but not how the returned objects can affect the order in which they are released.

那么为什么以前的函数会被编译器拒绝?为什么锁的保留时间似乎比预期的长?

So why is the former function rejected by the compiler? Why is the lock being seemingly retained for longer than expected?

推荐答案

这似乎是编译器中的错误.您可以使用显式的return语句使编译器满意:

This seems to be a bug in the compiler. You can make the compiler happy by using an explicit return statement:

use std::io::{stdin, BufRead};

fn foo() -> usize {
    let stdin = stdin();
    let stdinlock = stdin.lock();
    return stdinlock
        .lines()
        .count();
}

fn main() {}

游乐场

如评论中所述,存在与此相关的多个Rust问题:

As mentioned in the comments, there are multiple Rust issues related to this:

  • 37407
  • 21114

这篇关于返回使用StdinLock的结果时,为什么保留对stdin的借用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆