Using write_all() with a variable

I'm attempting to get a handle on reading and writing from and to files and one of the sources I found uses the write_all() method. Right now all I want to do is write some text to a file. My code works well when, using write_all(), I pass my text in between quotes in the write_all() method. However, my goal is to allow the user to enter text of his/her choice, store that text in a String, and then pass the string on to write_all() to save it in the file. I keep getting the error:

buffer.write_all(savetext.as_bytes()).expect("Cannot write data to file.");
   |                      ^^^^^^^^ help: a local variable with a similar name exists: `savetxt`

I've tried multiple ways of passing savetxt to write_all(), but keep getting the same error. So.....Help!??

Here is my current code:

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

fn main() -> std::io::Result<()> {
    let fname = "fefifofum.txt";
    let mut buffer = File::create(&fname).expect("Cannot create file.");
    
    let savetxt: String = String::from("This is the day that the Lord hath made!");

    buffer.write_all(savetext.as_bytes()).expect("Cannot write data to file.");
    Ok(())
}

And here is the base code I started with:


fn main() -> std::io::Result<()> {
    let mut buffer = File::create("foo.txt")?;

    buffer.write_all(b"some bytes")?;
    Ok(())
}

That base code comes from here.

Thanks for your help.

It seems like you have misspelled the name of your savetxt variable.

2 Likes

Well, that's embarassing. Thanks, Alice.

1 Like

@alice Actually, you still helped in a different way (than helping me proofread my work). There is a similar thread here on the forum and, when you were helping the person who posted the question, you suggested using as_bytes(). All the examples I could find used the syntax (b"text here") in the write_all() method. The 'b' kind of confuses me and it didn't work with the variable anyway. So, thanks twice, Alice! :smiley:

2 Likes

This is simply a way to make a "byte string", i.e. [u8; N] equivalent to the contents of corresponding string literal.

2 Likes

You're welcome.

1 Like

Does it only work in the (b"text here") format? I tried to find a way to make it work on a variable containing a string, but nothing I tried worked.

You can do "text".as_bytes()

1 Like

And that would work the same as b"text" ?

For your use-case, yes.

However, they're not completely the same. The type of "text".as_bytes() is &[u8], whereas b"text" has type &[u8; 4]. So, the length is only known as part of the type for one of them.

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.