How come i can't write_all to file?

I am watching a tutorial on how to write to file.

use std::fs::File;
use std::io::prelude;

fn main()
{
    let mut file = File::create("Testing.txt").expect("Could not run file!");
    file.write_all(b"Hello world").expect("something"); // Apparently there is an error
}

I get an error here after running cargo run

error[E0599]: no method named `write_all` found for type `std::fs::File` in the current scope
 --> src/main.rs:7:10
  |
7 |     file.write_all(b"Hello world").expect("something");
  |          ^^^^^^^^^
  |
  = help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope, perhaps add a `use` for it:
  |
1 | use std::io::Write;
  |

error: aborting due to previous error

For more information about this error, try `rustc --explain E0599`.
error: Could not compile `learning`.

Additionally I want to know what does file.write_all(b"Hello world") what does the b character mean?

This error says exactly what you can do to resolve it:

It means that the literal will be used not as &'static str, but as "binary string", i.e. &'static [u8, LENGTH] - playground showing this:

fn main() {
    let _: () = b"qwerty";
}

Error:

error[E0308]: mismatched types
 --> src/main.rs:2:17
  |
2 |     let _: () = b"qwerty";
  |                 ^^^^^^^^^ expected (), found reference
  |
  = note: expected type `()`
             found type `&'static [u8; 6]`

Note the found type bit.

1 Like

Oh ok thanks mate :slight_smile:

See also B - Operators and Symbols - The Rust Programming Language ...

b"..." Byte string literal; constructs a [u8] instead of a string

Your could would have worked if you changed this statement

use std::io::prelude;

to this one

use std::io::prelude::*;

the * means that everything from this module is imported (wildcard import) and std::io::Write is included in this import.

See here for the prelude module

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.