如何将格式化的字符串写入文件? [英] How do I write a formatted string to a file?

查看:48
本文介绍了如何将格式化的字符串写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将函数的输出写入文件.我希望 write_fmt 是我需要的:

使用 std::{fs::文件,io::{BufWriter, 写},};fn 主(){let write_file = File::create("/tmp/output").unwrap();让 mut writer = BufWriter::new(&write_file);//从我的函数让 num = 1;让阶乘 = 1;writer.write_fmt("{} = {} 的因子", num, factorial);}

错误

error[E0061]: 这个函数需要 1 个参数,但是提供了 3 个参数-->src/main.rs:11:12|11 |writer.write_fmt("{} = {} 的因子", num, factorial);|^^^^^^^^^^ 预期 1 个参数

这似乎是错误的,文档中没有太多可用的内容.

解决方案

文档 指出了这个问题:write_fmt 方法采用一个参数,类型为 std::fmt::Arguments,可以通过 format_args! 宏.它还建议了使用它的最佳方式:

<块引用>

write! 宏应该更倾向于调用此方法.

一个调用 write! (或 writeln!) 就像 println!,但是通过传递位置来写作为第一个参数:

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

(请注意,文档的每一页顶部都有一个搜索栏,因此您可以通过在其中搜索 ! 来查找有关宏等的文档.)>

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.

解决方案

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.)

这篇关于如何将格式化的字符串写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆