gpt4 book ai didi

rust - 当返回使用 StdinLock 的结果时,为什么保留对 stdin 的借用?

转载 作者:行者123 更新时间:2023-11-29 07:48:55 25 4
gpt4 key购买 nike

给定以下函数:

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)的结果不会保留对原始源的任何引用。事实上,在返回之前将相同的结果分配给绑定(bind)就可以了(Playground)。

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

这表明立即返回“消耗的锁”会导致锁试图比锁定的内容存活更长时间,这是一种非常不寻常的方式。我调查过的所有引用资料通常都指出声明的顺序很重要,但没有指出返回的对象如何影响它们的释放顺序。

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

最佳答案

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

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

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

fn main() {}

playground

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

关于rust - 当返回使用 StdinLock 的结果时,为什么保留对 stdin 的借用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179123/

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