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

问题描述

给定以下函数:

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

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

编译失败,错误如下:

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)没有保留对原始源的任何引用.事实上,在返回之前为绑定分配相同的结果就可以正常工作(Playground).

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:

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

09-02 11:25