file:File or file:Result.. How to write if file is Result

VSCode + rustanaliser + Win11home says:
file1 is File
file2 is Result
Why? How ?
I cannot add text to file2, file1 works just fine..
How to add some text to file, when it is Result ?

    use std ::  fs  ::  OpenOptions ;
    use std ::  io  ::  Write   ;

    let mut file1 = OpenOptions  :: new()  .create(  true  )  .   append  (   true    )   .open   (   "data1.txt"  )   .   expect(
        "cannot open file"  )   ;
    file1    .   write_all   (   "\nHello World"   .   as_bytes    (   )  )    .   expect  (   "write failed"  )   ;
    file1    .   write_all   ("\nTutorialsPoint11111111" .   as_bytes    (   )   )   .   expect  ("write failed" )   ;
    println !   (   "f1  file append success"   )   ;




  let file2 = OpenOptions::new()
            //   .read(!true)
              .append(true)
              .create(true)
              .open("foo.txt");
 println !   (   "f2  {:?}"  ,file2 )   ;
 


        // std ::  fs  ::write( file2   ,  "dddddddd")     ;
             
            //   if let Err(e) = writeln!(file2, "A new line!") {
            //     eprintln!("Couldn't write to file: {}", e);
            // }
//   file2.

open(...) returns a Result<File, std::io::Error> which can either be an Ok(File) or an Err(io::Error).

When you opened file1, you then called expect() on the returned Result:

let mut file1 = OpenOptions::new()
    .create(true)
    .append(true)
    .open("data1.txt")
    .expect("cannot open file"); // <-- here

The expect will panic (terminating your program with the error "cannot open file") if the Result is Err, or return the File if the Result is Ok.

When you opened file2, you didn't call expect, so you still have the Result<File, io::Error>. You need to pull the file out of the Ok if it is Ok, or handle the Err if it is not. (If you just want to panic if there was a problem opening the file, you can use expect again.)

2 Likes

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.