Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

tcp - If BufReader takes ownership of a stream, how can I read and write lines on it?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution: use references.

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

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> { ... }
}

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

impl<'a> Read for &'a TcpStream

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

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

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

impl<'a> Write for &'a TcpStream

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...