Stream Copy With io::copy
Move bytes between readers and writers with io::copy, including an infinite repeat reader bounded by take and a discarding sink.
Code
use std::io::{self, Cursor, Read};
fn main() -> io::Result<()> {
// copy 返回搬运的字节数,内部使用固定大小缓冲区
let mut source = Cursor::new(b"streamed payload");
let mut sink_bytes = Vec::new();
let copied = io::copy(&mut source, &mut sink_bytes)?;
println!("copied: {copied} -> {}", String::from_utf8_lossy(&sink_bytes));
// io::repeat 产生无限字节流,用 take 限定总量
let mut endless = io::repeat(b'=').take(8);
let mut padding = String::new();
endless.read_to_string(&mut padding)?;
println!("padding: {padding}");
// io::sink 丢弃写入,只统计体积
let mut discard = io::sink();
let dropped = io::copy(&mut Cursor::new(vec![0u8; 1024]), &mut discard)?;
println!("discarded: {dropped}");
// copy 也适用于任何实现 Read/Write 的类型
let mut target = Vec::new();
let mut limited = Cursor::new(b"chunk-one-chunk-two").take(9);
let moved = io::copy(&mut limited, &mut target)?;
println!("limited copy: {moved} -> {}", String::from_utf8_lossy(&target));
Ok(())
}How the snippet works
Stream Copy With io::copy reduces to the function main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
Signature: fn main() -> io::Result<()>
Running the file prints labeled results such as copied:, padding:, discarded: — each operation’s effect is visible in the output.
Key statements
let dropped = io::copy(&mut Cursor::new(vec![0u8; 1024]), &mut discard)?;
let mut limited = Cursor::new(b"chunk-one-chunk-two").take(9);
let copied = io::copy(&mut source, &mut sink_bytes)?;
Interactive Tools for This Topic
FAQ
- How do errors reach the caller?
- Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
- What does Stream Copy With io::copy print when run?
- Running the file directly is enough — expect labeled output lines such as `copied:`, `padding:`, `discarded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.