Rust ?运算符 Rust读写txt文件

一、Rust ?运算符
?运算符:传播错误的一种快捷方式。
  • 如果Result是Ok:Ok中的值就是表达式的结果,然后继续执行程序。

  • 如果Result是Err:Err就是整个函数的返回值,就像使用了return

?运算符只能用于返回Result的函数。
?运算符与main函数
  • main函数返回类型是:()

  • main函数的返回类型也可以是:Result<T,E>

  • Box是trait对象,简单理解:"任何可能的错误类型"

二、Rust读写txt文件

Rust可以对txt文件读、写、创建、添加、打开操作。

rust 复制代码
use std::fs::{self, OpenOptions};

let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .append(true)
        .open(filepath)?;
三、Rust实例测试

main.rs

rust 复制代码
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};


fn main() -> Result<(), Box<dyn std::error::Error>> {
    let filepath = "test1.txt";
    let filepath2 = "test2.txt";

    let str = read_file_string(filepath);
    println!("{:#?}", str);

    let vec = read_file_vec(filepath);
    println!("{:#?}", vec);

    read_file_buffer(filepath)?;
    write_file_buffer(filepath2)?;

    Ok(())
}

//将整个文件作为字符串读取
fn read_file_string(filepath: &str) -> Result<String, Box<dyn std::error::Error>> {
    let data = fs::read_to_string(filepath)?;
    Ok(data)
}

//将整个文件作为Vector读取
fn read_file_vec(filepath: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let data = fs::read(filepath)?;
    Ok(data)
}

//BufReader按行读取
fn read_file_buffer(filepath: &str) -> Result<(), Box<dyn std::error::Error>> {
    let file = OpenOptions::new().read(true).open(filepath)?;
    let reader = BufReader::new(file);

    //按行读取
    for line in reader.lines() {
        let str: String = line.unwrap();
        println!("{}", str);
    }

    Ok(())
}

//BufWriter带缓冲写入
fn write_file_buffer(filepath: &str) -> Result<(), Box<dyn std::error::Error>> {
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(filepath)?;

    let mut reader = BufWriter::new(file);

    // 带缓冲写入
    reader.write(b"hello\n")?;
    reader.write(b"word\n")?;
    //确保缓冲中的内容全部写入文件
    reader.flush()?;

    Ok(())
}

其中test1.txt文件内容如下:

rust 复制代码
白日依山尽,
黄河入海流。

运行效果如下:

生成的test2.txt文件,内容如下:

rust 复制代码
hello
word

相关推荐
花褪残红青杏小14 小时前
Rust图像处理第8节-暗角 & 复古胶片特效:四周衰减中心高亮
rust·webassembly·图形学
独孤留白1 天前
从C到Rust:Rust 的 Trait 不是Interface,那是什么?
rust
花褪残红青杏小2 天前
Rust图像处理第7节-马赛克像素化:分块取平均色实现打码风格
rust·webassembly·图形学
doiito2 天前
【Agent Harness】Gliding Horse 设计细节 -- 不跟风开发自己的AI Agent
架构·rust·agent
doiito2 天前
【Agent Harness】Gliding Horse 核心设计理念,不跟风开发自己的AI Agent
ai·rust·架构设计·系统设计·ai agent
花褪残红青杏小3 天前
Rust图像处理第6节- 均值模糊 & 中值模糊:3×3 邻域的两种经典玩法
rust·webassembly·图形学
子兮曰3 天前
前端工具链的「Rust 化」:一场没有赢家的军备竞赛?
前端·后端·rust
星栈3 天前
写 Dioxus Demo 不难,难的是把它写成项目
前端·rust·前端框架
mCell3 天前
【锐评】桌面端技术营销:别拿跑分当工程判断
前端·rust·electron
武子康3 天前
调查研究-201 Rust 里的 dev build 和 release build:为什么同一份代码性能差这么多?
后端·架构·rust