Rust-IO

这篇具有很好参考价值的文章主要介绍了Rust-IO。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

In Rust, input and output (I/O) operations are mainly handled through the std::io module, which provides a number of important functionalities for performing I/O operations. Here’s a quick overview of some of the key features provided by std::io.

Read and Write Traits

Two of the most important traits for I/O operations in Rust are Read and Write. These traits provide methods that allow bytes to be read from and written to streams respectively.

For example, any type that implements the Read trait will provide a method read(&mut self, buf: &mut [u8]) -> Result<usize>, which reads data into buf and returns the number of bytes read. Similarity, any type that implements the Write trait provides a method write(&mut self, buf: &[u8]) -> Result<usize>, which writes the bytes from buf and returns the number of bytes written.

Standard Input and Output

The std::io module also provides functionality for interacting with the standard input (stdin), standard output (stdout), and standard error (stderr) streams. For example:

use std::io::{self, Write};

fn main() -> io::Result<()> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    io::stdout().write_all(input.as_bytes())?;

    Ok(())
}

In this example, read_line is called on the standard input to read a line from the user, and then write_all is called on the standard output to write this line out.

Files

The File struct represents a file on the filesystem and it implements both the Read and Write traits, so you can perform I/O operations on files. Here’s an example:

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

fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;

    let mut file = File::create("bar.txt")?;
    file.write_all(contents.as_bytes())?;

    Ok(())
}

In this example, the file foo.txt is opened and read into a string. Then, a new file bar.txt is created, and the contents of the string are written into it.

Buffered I/O

The std::io module provides BufReader and BufWriter structs for buffered I/O operations. These wrap readers and writers and buffer their input and output, which can improve performance for certain types of I/O operations.

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

fn main() -> std::io::Result<()> {
    let file = File::open("foo.txt")?;
    let mut buf_reader = BufReader::new(file);
    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;

    println!("{}", contents);
    Ok(())
}

In this example, a BufReader is created from a File. This BufReader can then be used to read from the file more efficiently.

Errors

Most operations in std::io return the Result type, which represents either a successful result (an Ok(T) variant), or an error (an Err(E) variant). This allows Rust to express I/O operations that could fail in a way that must be handled by your code. The ? operator can be used to propagate these errors up the call stack.

A comprehensive case is as follows:

use std::io::Write;
fn main() {

    /*
        std::io::stdin() 返回标准输入流stdin的句柄。
        read_line() stdin的句柄的一个方法,从标准输入流中读取一行数据
        返回一个Result枚举。会自动删除行尾的换行符\n。
        unwrap() 是一个帮助的方法,简化恢复错误的处理。返回Result中的存储实际值。
     */
    let mut in_word = String::new();
    let result = std::io::stdin().read_line(&mut in_word).unwrap();
    println!("您输入的是:{}\n", in_word);       // 您输入的是:hello
    println!("读取的字节数为:{}\n", result);    // 读取的字节数为:7

    let result1 = std::io::stdout().write("Rust".as_bytes()).unwrap();
    println!("写入的字节数为:{}\n", result1);   // Rust写入的字节数为:4
    let result2 = std::io::stdout().write("Hello".as_bytes()).unwrap();
    println!("写入的字节数为:{}\n", result2);   // Hello写入的字节数为:5

    /*
        std::io::stdout()返回标准输出流的句柄。
        write()是标准输出流stdout的句柄上的一个方法,用于向标准输出流中写入字节流的内容。
        也放回一个Result枚举,不会输出结束时自动追加换行符\n
     */

    let input_args = std::env::args();
    for arg in input_args {
        println!("命令行参数:{}", arg);
    }

    /*
        输出:
        命令行参数:D:\Rust\io_23\target\debug\io_23.exe
        命令行参数:Rust
        命令行参数:Programming
        命令行参数:Language
     */
}

unwrap()

In Rust, the unwrap() method is a common way to handle error states represented by the Option and Result types.

Let’s break it down a bit:

  • Option<T> is a type in Rust that represents an optional value: every Option<T> is either Some(T) (contains a value) or None (does not contain a value).

  • Result<T, E> is a type in Rust that can represent either success (Ok(T)) or failure (Err(E)).

Both Option and Result types have the method unwrap(). For an Option, calling unwrap() returns the contained value if it’s Some(T), but if it’s None, it will cause the program to panic (crash).

For a Result, calling unwrap() returns the contained value if it’s Ok(T), but if it’s Err(E), it will also cause the program to panic.

So, the unwrap() method is a somewhat risky operation to use, because while it’s a quick and easy way to obtain the inner value, it can cause your program to crash if the Option is None or the Result is an Err. In production code, it’s often preferable to handle errors more gracefully rather than using unwrap().文章来源地址https://www.toymoban.com/news/detail-616659.html

到了这里,关于Rust-IO的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【跟小嘉学 Rust 编程】十四、关于 Cargo 和 Crates.io

    【跟小嘉学 Rust 编程】一、Rust 编程基础 【跟小嘉学 Rust 编程】二、Rust 包管理工具使用 【跟小嘉学 Rust 编程】三、Rust 的基本程序概念 【跟小嘉学 Rust 编程】四、理解 Rust 的所有权概念 【跟小嘉学 Rust 编程】五、使用结构体关联结构化数据 【跟小嘉学 Rust 编程】六、枚举

    2024年02月11日
    浏览(38)
  • rust crate.io 配置国内源(cargo 国内源) warning: spurious network error (2 tries remainin...

    rust 笔记 Crate 国内源配置 作者 : 李俊才 (jcLee95):https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343 邮箱 : 291148484@163.com 本文地址 :https://blog.csdn.net/qq_28550263/article/details/130758057 Rust 官方默认的 Cargo 源服务器为 crates.io,其同时也是 Rust 官方的 crate 管理仓库,但是由于官方服

    2024年02月05日
    浏览(36)
  • 研读Rust圣经解析——Rust learn-15(unsafe Rust )

    Rust 还隐藏有第二种语言,它不会强制执行这类内存安全保证:这被称为 不安全 Rust(unsafe Rust) 不安全 Rust 之所以存在,是因为静态分析本质上是保守的。当编译器尝试确定一段代码是否支持某个保证时,拒绝一些合法的程序比接受无效的程序要好一些。这必然意味着有时

    2024年02月01日
    浏览(26)
  • 【Rust】Rust学习 第十七章Rust 的面向对象特性

    面向对象编程(Object-Oriented Programming,OOP)是一种模式化编程方式。对象(Object)来源于 20 世纪 60 年代的 Simula 编程语言。这些对象影响了 Alan Kay 的编程架构中对象之间的消息传递。他在 1967 年创造了  面向对象编程  这个术语来描述这种架构。关于 OOP 是什么有很多相互矛

    2024年02月11日
    浏览(32)
  • 【Rust教程 | 基础系列1 | Rust初相识】Rust简介与环境配置

    Rust是一种系统编程语言,专注于速度、内存安全和并行性。它的设计目标是提供一种能够实现高性能系统的语言,同时保证内存安全和线程安全。 本篇教程的目标是通过融合理论与实践,帮助读者更快速、更有效地学习 Rust,并解决在学习过程中可能遇到的挑战。这些内容也

    2024年02月15日
    浏览(55)
  • 【Rust 基础篇】Rust 闭包

    在 Rust 中,闭包(closures)是一种函数对象,它可以捕获其环境中的变量,并在需要时调用。闭包提供了一种方便的方式来封装行为,并在需要时进行调用。本篇博客将详细介绍 Rust 中的闭包,包括闭包的定义、语法、捕获变量的方式以及一些常见的使用场景。 闭包在 Rust 中

    2024年02月16日
    浏览(30)
  • 【Rust学习】安装Rust环境

    本笔记为了记录学习Rust过程,内容如有错误请大佬指教 使用IDE:vs code 参考教程:菜鸟教程链接: 菜鸟教程链接: 因为我已经安装过VSCode了,所以VSCode的安装方法在此处就不多介绍了,接下来就是安装Rust的编译工具。 Rust 编译工具 可以点击跳转下载Rust 编译工具 新建文件夹,

    2024年01月17日
    浏览(50)
  • 【Rust 基础篇】Rust 封装

    在 Rust 中,封装是一种面向对象编程的重要概念,它允许将数据和相关的方法组合在一起,形成一个独立的单元。通过封装,我们可以隐藏数据的实现细节,只暴露需要对外部使用的接口,从而提高代码的可维护性和安全性。本篇博客将详细介绍 Rust 中封装的概念,包含代码

    2024年02月16日
    浏览(56)
  • Rust 性能优化 : Rust 性能优化技巧,提升 Rust 程序的执行效率和资源利用率 The Rust Performance

    作者:禅与计算机程序设计艺术 在过去的几年中,随着编程语言的快速发展,编程人员已经逐渐从依赖编译型语言转向了使用解释型语言。相对于编译型语言来说,解释型语言具有更快的执行速度,在某些情况下甚至可以实现接近编译器的运行时效率。但是另一方面,这些语

    2024年02月07日
    浏览(44)
  • 【Rust 基础篇】Rust FFI:连接Rust与其他编程语言的桥梁

    Rust是一种以安全性和高效性著称的系统级编程语言,具有出色的性能和内存安全特性。然而,在现实世界中,我们很少有项目是完全用一种编程语言编写的。通常,我们需要在项目中使用多种编程语言,特别是在与现有代码库或底层系统交互时。为了实现跨语言的互操作性,

    2024年02月15日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包