学习Rust的第25天:Rust中的mkdir

2024-05-03 10:28
文章标签 rust 学习 25 mkdir

本文主要是介绍学习Rust的第25天:Rust中的mkdir,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

为了实现重建 GNU 核心实用程序的崇高目标,今天的工具是 mkdir 我们用来在 Linux 上创建目录的工具。让我们开始吧。

Pseudo Code 伪代码

args = command_line_arguments
remove the first element of the args vector
if args.length == 0 {print error_message
}
else if args.contains("--help") {print help_message
} else {for directory_name in args {create_directory(directory_name)}
}

Okay that looks simple enough let’s start with new cargo library crate and create a simple struct and a new function
好吧,看起来很简单,让我们从新的货物库箱开始,创建一个简单的结构体和一个 new 函数

pub struct Config<'a>{pub dir_names: &'a Vec<String>
}impl Config<'_>{pub fn new(args: &Vec<String>) -> Config {Config {dir_names: args}}
}

Let’s make our work a little bit easier by creating private functions for help and not_enough_arguments
让我们为 help 和 not_enough_arguments 创建私有函数,让我们的工作变得更容易一些

impl Config<'_>{pub fn new(args: &Vec<String>) -> Config{Config { dir_names: args }}fn not_enough_arguments(){eprintln!("mkdir: missing operand");eprintln!("For help use: mkdir --help");}fn help(){eprintln!("This is a cheap little clone of the mkdir utility in the GNU core utilities, the catch is that I made it in rust, check out more of my work at medium: https://shafinmurani.medium.com");eprintln!("To use this util: mkdir folder_name1 folder_name2 ... folder_nameN");}}

Now that the basics are setup, we will create a binary crate, main.rs
现在基础知识已经设置完毕,我们将创建一个二进制板条箱, main.rs

use mkdir::Config; //use your cratename::structName here
use std::env;fn main(){let mut args: Vec<String> = env::args.collect();args.remove(0);let config == Config::new(&args);
}

This will instantiate our Config struct, now getting to the important part…
这将实例化我们的 Config 结构,现在进入重要部分......

To create a directory, there are two functions in the fs crate , fs::create_dir() and fs::create_dir_all() . I will leave you with the task to find their differences and why we will be using create_dir_all(). Here’s a resource for you to research it create_dir() and create_dir_all()
要创建目录, fs crate 中有两个函数, fs::create_dir() 和 fs::create_dir_all() 。我将留给您找出它们的差异以及为什么我们将使用 create_dir_all() 的任务。这里有一个资源供您研究 create_dir() 和 create_dir_all()

Let’s create a function which will create a directory in out impl block…
让我们创建一个函数,它将在 impl 块中创建一个目录......

fn create_dir(dir: String) -> std::io::Result<()> {fs::create_dir_all(dir)?;Ok(())
}

It returns a Result indicating success or failure, As of now here’s what our lib.rs file looks like
它返回一个 Result 指示成功或失败,到目前为止,这是我们的 lib.rs 文件的样子

pub struct Config<'a>{pub dir_names: &'a Vec<String>
}impl Config<'_>{pub fn new(args: &Vec<String>) -> Config{Config { dir_names: args }}fn not_enough_arguments(){eprintln!("mkdir: missing operand");eprintln!("For help use: mkdir --help");}fn help(){eprintln!("This is a cheap little clone of the mkdir utility in the GNU core utilities, the catch is that I made it in rust, check out more of my work at medium: https://shafinmurani.medium.com");eprintln!("To use this util: mkdir folder_name1 folder_name2 ... folder_nameN");}fn create_dir(dir: String) -> std::io::Result<()> {fs::create_dir_all(dir)?;Ok(())}}

Now we have everything we’ll need to make a directory, so let’s make one?
现在我们已经拥有了制作目录所需的一切,那么让我们制作一个目录吧?

We will create a run function, which takes a reference to self and call our private function in there according to the conditons we specified in out pseudo code
我们将创建一个 run 函数,它引用 self 并根据我们在伪代码中指定的条件调用我们的私有函数

pub fn run(&self){if self.dir_names.len() == 0 {Self.not_enough_arguments();} else if self.dir_names.contains(&String::from("--help")) {Self.help();} else {for dir in self.dir_names {let result = Self::create_dir(dir.to_string());}}
}

This program does work but we don’t really have any error handling taking place here…
该程序确实有效,但我们实际上没有进行任何错误处理......

Let’s fix that 让我们解决这个问题

pub fn run(&self){if self.dir_names.len() == 0 {Self.not_enough_arguments();} else if self.dir_names.contains(&String::from("--help")) {Self.help();} else {for dir in self.dir_names {let result = Self::create_dir(dir.to_string());match result {Ok(()) => {},Err(e) => {eprintln!("{}",e)},};}}
}

Now we can call the run function in our main.rs file…
现在我们可以在 main.rs 文件中调用 run 函数......

use mkdir::Config;
use std::env;
fn main() {let mut args: Vec<String> = env::args().collect();args.remove(0);let config = Config::new(&args);config.run();
}

GitHub 仓库:shafinmurani/gnu-core-utils-rust (github.com)

Summary 概括

Lib.rs 库

  • Defines a Rust library module.
    定义 Rust 库模块。
  • Contains the Config struct and its implementation.
    包含 Config 结构及其实现。
  • Config struct:  Config 结构:
  • Holds a reference to a vector of strings (dir_names) representing directory names to be created.
    保存对表示要创建的目录名称的字符串向量 ( dir_names ) 的引用。

Implementation block impl Config<'_>:
实现块 impl Config<'_> :

  • new function:  new 功能:
  • Constructs a new Config instance, taking a reference to a vector of strings (args) as input.
    构造一个新的 Config 实例,将对字符串向量 ( args ) 的引用作为输入。

not_enough_arguments function:  not_enough_arguments 功能:

  • Prints an error message to standard error if no directory names are provided as arguments.
    如果没有提供目录名称作为参数,则将错误消息打印到标准错误。

help function:  help 功能:

  • Prints a help message to standard error explaining how to use the program.
    将帮助消息打印到标准错误,解释如何使用该程序。

create_dir function:  create_dir 功能:

  • Attempts to create a directory specified by the input string using the fs::create_dir_all function from the standard library. It returns a Result indicating success or failure.
    尝试使用标准库中的 fs::create_dir_all 函数创建由输入字符串指定的目录。它返回一个 Result 指示成功或失败。

run function:  run 功能:

  • Executes the logic of the program.
    执行程序的逻辑。
  • If no directory names are provided, it prints a “missing operand” error message.
    如果未提供目录名称,则会打印“缺少操作数”错误消息。
  • If the --help argument is provided, it prints the help message.
    如果提供了 --help 参数,它将打印帮助消息。
  • Otherwise, it iterates through the provided directory names, attempting to create each directory and printing any encountered errors.
    否则,它会迭代提供的目录名称,尝试创建每个目录并打印遇到的任何错误。

Main.rs

  • Defines the entry point of the program.
    定义程序的入口点。
  • Imports the Config struct from the mkdir module (defined in lib.rs) using use mkdir::Config.
    使用 use mkdir::Config 从 mkdir 模块(在 lib.rs 中定义)导入 Config 结构体。
  • Imports the env module from the standard library, used to access command-line arguments.
    从标准库导入 env 模块,用于访问命令行参数。
  • main function:  main 功能:
  • Retrieves command-line arguments using env::args() and collects them into a vector (args).
    使用 env::args() 检索命令行参数并将它们收集到向量中 ( args )。
  • Removes the first argument, which is the name of the program itself, using args.remove(0).
    使用 args.remove(0) 删除第一个参数,即程序本身的名称。
  • Constructs a Config instance (config) with the remaining arguments using Config::new(&args).
    使用 Config::new(&args) 构造一个 Config 实例 ( config ) 以及其余参数。
  • Calls the run method on the config instance to execute the program's logic.
    调用 config 实例上的 run 方法来执行程序的逻辑。

这篇关于学习Rust的第25天:Rust中的mkdir的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/956523

相关文章

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Rust中的注释使用解读

《Rust中的注释使用解读》本文介绍了Rust中的行注释、块注释和文档注释的使用方法,通过示例展示了如何在实际代码中应用这些注释,以提高代码的可读性和可维护性... 目录Rust 中的注释使用指南1. 行注释示例:行注释2. 块注释示例:块注释3. 文档注释示例:文档注释4. 综合示例总结Rust 中的注释

Rust格式化输出方式总结

《Rust格式化输出方式总结》Rust提供了强大的格式化输出功能,通过std::fmt模块和相关的宏来实现,主要的输出宏包括println!和format!,它们支持多种格式化占位符,如{}、{:?}... 目录Rust格式化输出方式基本的格式化输出格式化占位符Format 特性总结Rust格式化输出方式

Rust中的Drop特性之解读自动化资源清理的魔法

《Rust中的Drop特性之解读自动化资源清理的魔法》Rust通过Drop特性实现了自动清理机制,确保资源在对象超出作用域时自动释放,避免了手动管理资源时可能出现的内存泄漏或双重释放问题,智能指针如B... 目录自动清理机制:Rust 的析构函数提前释放资源:std::mem::drop android的妙

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

浅析Rust多线程中如何安全的使用变量

《浅析Rust多线程中如何安全的使用变量》这篇文章主要为大家详细介绍了Rust如何在线程的闭包中安全的使用变量,包括共享变量和修改变量,文中的示例代码讲解详细,有需要的小伙伴可以参考下... 目录1. 向线程传递变量2. 多线程共享变量引用3. 多线程中修改变量4. 总结在Rust语言中,一个既引人入胜又可

Rust 数据类型详解

《Rust数据类型详解》本文介绍了Rust编程语言中的标量类型和复合类型,标量类型包括整数、浮点数、布尔和字符,而复合类型则包括元组和数组,标量类型用于表示单个值,具有不同的表示和范围,本文介绍的非... 目录一、标量类型(Scalar Types)1. 整数类型(Integer Types)1.1 整数字

五大特性引领创新! 深度操作系统 deepin 25 Preview预览版发布

《五大特性引领创新!深度操作系统deepin25Preview预览版发布》今日,深度操作系统正式推出deepin25Preview版本,该版本集成了五大核心特性:磐石系统、全新DDE、Tr... 深度操作系统今日发布了 deepin 25 Preview,新版本囊括五大特性:磐石系统、全新 DDE、Tree