1
votes
use std::env;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};

fn main() {
    let args = env::args().collect::<Vec<String>>();
    let file = File::open(&args[1]).expect("file not found");
    let reader = BufReader::new(file);
    let mut writer = BufWriter::new(std::io::stdout());
    for it in reader.bytes() {
        writer.write(&[*it]);
    }
}

Why does this give an error?

type `std::result::Result<u8, std::io::Error>` cannot be dereferenced
1
What exactly are you trying to do? reader.bytes() gives you a fallible iterator over u8, i.e. an iterator whose item is Result<u8, io::Error>. As the error message tells you, a Result<u8, Error> cannot be dereferenced. You at least need let it = it.unwrap() or equivalent, but even then you'll get a u8, which again cannot be referenced. Something like writer.writer(&[it.unwrap()]) should work just fine, though. - user4815162342

1 Answers

2
votes

From the documentation,

fn bytes(self) -> Bytes<Self> where
    Self: Sized, 

Transforms this Read instance to an Iterator over its bytes.

The returned type implements Iterator where the Item is Result<u8, io::Error>. The yielded item is Ok if a byte was successfully read and Err otherwise. EOF is mapped to returning None from this iterator.

Only types implementing std::ops::Deref can be dereferenced.

use std::env;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};

fn main() {
    let args = env::args().collect::<Vec<String>>();
    let file = File::open(&args[1]).expect("file not found");
    let reader = BufReader::new(file);
    let mut writer = BufWriter::new(std::io::stdout());
    for it in reader.bytes() {
        writer.write(&[it.unwrap()]);
    }
}