本文介绍了如果 BufReader 获得流的所有权,我如何在其上读写行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 TCPStream 中读取一行,向其中写入另一行,然后重复.问题是 BufReader::new 拥有我的 TCPStream 变量:

I want to read a line from a TCPStream, write another line to it, and then repeat. The issue is that BufReader::new takes ownership of my TCPStream variable:

let stream = ...; // TCPStream

let reader = BufReader::new(stream); // moved its value

// can't use stream here anymore

对此有什么简单的解决方案?

What is a simple solution to this?

推荐答案

解决方案:使用引用.

let mut stream = ...;
let reader = BufReader::new(&stream);
let writer = BufWriter::new(&stream);

说明

如果我们仔细看看 BufReader::new,我们会发现它接受一个 R 类型的参数 inner,其中 R 只是任何实现 Read 的类型:


Explanation

If we take a closer look at BufReader::new, we see that it takes an argument inner of type R, where R is just any type that implements Read:

impl<R: Read> BufReader<R> {
    pub fn new(inner: R) -> BufReader<R> { ... }
}

然后我们看一下Read,看看这个实现:

We then take a look at Read and see this implementation:

impl<'a> Read for &'a TcpStream

所以我们可以只传递一个对 new 函数的引用,就像这样:

So we can just pass a reference to the new function, like so:

let reader = BufReader::new(&stream);

我们将对 BufWriterWrite 做同样的事情,并会看到确实有这个实现:

We will do the same for BufWriter and Write and will see that indeed there is this implementation:

impl<'a> Write for &'a TcpStream

所以我们可以再次使用不可变引用来创建 BufWriter.

So we can, again, use an immutable reference to create the BufWriter.

这篇关于如果 BufReader 获得流的所有权,我如何在其上读写行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:59