Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

rust - How do I write a formatted string to a file?

I want to write output of my function to a file. I expected that write_fmt is what I require:

use std::{
    fs::File,
    io::{BufWriter, Write},
};

fn main() {
    let write_file = File::create("/tmp/output").unwrap();
    let mut writer = BufWriter::new(&write_file);

    // From my function
    let num = 1;
    let factorial = 1;

    writer.write_fmt("Factorial of {} = {}", num, factorial);
}

Error

error[E0061]: this function takes 1 parameter but 3 parameters were supplied
  --> src/main.rs:11:12
   |
11 |     writer.write_fmt("Factorial of {} = {}", num, factorial);
   |            ^^^^^^^^^ expected 1 parameter

This seems wrong and there isn't much available in the documentation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The documentation indicates the issue: the write_fmt method takes one argument, of type std::fmt::Arguments, which can be constructed via the format_args! macro. It also suggests the best way to use it:

The write! macro should be favored to invoke this method instead.

One calls write! (or writeln!) just like println!, but by passing the location to write to as the first argument:

write!(&mut writer, "Factorial of {} = {}", num, factorial);

(Note that the docs have a search bar at the top of each page, so one can find documentation on, for example, macros by searching for <name>! there.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...