Writeln! value used here after move

Hi, i try this fragment into function that return io::Result<()>

...
    let mut movies_txt = File::create("/home/pichibw/premieres.txt");
    writeln!(movies_txt?, "aaa\n");
    writeln!(movies_txt?, "bbb\n");
...

Error:
let mut movies_txt = File::create("/home/pichibw/premieres.txt");
| ------------------- move occurs because movies_txt has type Result<File, std::io::Error>, which does not implement the Copy trait
794 | writeln!(movies_txt?, "aaa\n");
| ---------------- movies_txt moved due to this method call
795 | writeln!(movies_txt?, "bbb\n");
| ^^^^^^^^^^^^^^^ value used here after move
|
note: branch takes ownership of the receiver self, which moves movies_txt
--> /rustc/2c8cc343237b8f7d5a3c3703e3a87f2eb2c54a74/library/core/src/ops/try_trait.rs:218:15

The ? operator consumes the expression before it to return the Ok/Some variant. Moving the ? to the creation of the file should fix this:

let mut movies_txt = File::create("/home/pichibw/premieres.txt")?;
writeln!(movies_txt, "aaa\n");
writeln!(movies_txt, "bbb\n");
3 Likes

(Plus a ? on every write.)

3 Likes

:hugs:thanks

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.