Compilation error in Progamming Rust by Blandy

I have been working through "Programming Rust" by Jim Blandy. In the chapter 11 on traits there is a small sample that I can't get to compile

use std::io::Write;
fn say_hello(out: &mut dyn Write) -> std::io::Result<()> { 
//fn say_hello<W: Write>(out: &mut W) -> std::io::Result<()> {
    out.write_all(b"hello world\n")?;
    out.flush();
    Ok(())
}

fn main() {
    //use std::fs::File::Write;
    use std::fs::File;

    let mut local_file = File::create("hello.txt");
    say_hello(&mut local_file);
}

This gives an error:

 say_hello(&mut local_file);
   |               ^^^^^^^^^^^^^^^ the trait `std::io::Write` is not implemented for `std::result::Result<std::fs::File, std::io::Error>`
   |
   = note: required for the cast to the object type `dyn std::io::Write`

I have tried hard to fix it but I am just not getting it.

Any advice?

Thanks,

Frank

File::create returns a Result since there is a chance of failure.

You need to unwrap it first.

let mut local_file = File::create("hello.txt").expect("Unable to create new file");

Thanks!!. Your example of the fix allowed me to see on the type of local_file shifted by the unwrapping with .expect. std::result::Result<std::fs::File, std::io::Error>

was driving me a bit crazy as I am only half way through the book and at the beginning of the traits chapter.

Frank

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.