学习Rust的第27天:Rust中的pwd

过去几天我们一直在重新创建 GNU 核心实用程序的基本功能,而今天,我们将做一些有点太简单的事情, pwd 这个实用程序是用于打印Linux终端中的工作目录。

Understanding the utility
了解实用程序

Running the pwd command, we get an output like this
运行 pwd 命令,我们得到如下输出

# pwd
/root/

Here /root is the directory that we are currently in, in the Linux Shell
这里 /root 是我们当前所在的目录,在 Linux Shell 中

To recreate this, it’s really not difficult and we can recreate this without any trouble using the std::env::current_dir() function, Let’s create a library crate inside a new Rust project and a module to get started with this.
要重新创建它,实际上并不困难,我们可以使用 std::env::current_dir() 函数毫无困难地重新创建它,让我们在新的 Rust 项目中创建一个库箱和一个模块来开始使用它。

//lib.rs

pub mod dir_get {
  use std::env;
  use std::path::PathBuf;

  fn get_working_directory() -> std::io::Resullt<PathBuf> {
    env::current_dir()
  }
}

The get_working_directoryfunction runs the env::current_dir() function and returns a result enum with a PathBuf or an Err variant.
get_working_directory 函数运行 env::current_dir() 函数并返回带有 PathBuf 或 Err 变体的结果枚举。

We will do the error handing in the next part…
我们将在下一部分中进行错误处理......

According to the documentation of this ffunction we can see that there are two cases in which this function will return an error:
根据这个ffunction的文档我们可以看到这个函数有两种情况会返回错误:

  • Current directory does not exist.
    当前目录不存在。
  • There are insufficient permissions to access the current directory.
    没有足够的权限访问当前目录。

Check out the documentation here :
查看此处的文档:
current_dir in std::env - Rust (rust-lang.org)

Now to create a function which prints the PathBuf while handling the errors :
现在创建一个在处理错误时打印 PathBuf 的函数:

//lib.rs

pub mod dir_get {
  use std::env;
  use std::path::PathBuf;

  fn get_working_directory() -> std::io::Resullt<PathBuf> {
    env::current_dir()
  }

  pub fn print_working_dir() {
    let result = get_working_directory();
    match result {
      Ok(path_buf) => println!("{}",path_buf.as_path().display()),
      Err(e) => eprintln!("Application Error: {}",e),
    };
  }
}

Now that’s all we’ll have to do with the library crate, let’s get to the main.rs file and call the print_working_dirfunction there and check if it works?
现在这就是我们对库箱要做的所有事情,让我们进入 main.rs 文件并调用其中的 print_working_dir 函数并检查它是否有效?

//main.rs
use pwd::dir_get; //use the name of your crate and module here

fn main(){
  dir_get::print_working_dir();
}

And it’s done, running the program with cargo run we get the following response
就完成了,使用 cargo run 运行程序,我们得到以下响应

# pwd #The GNU utility
/root/learning_rust/linux_tools/pwd
# cargo run #The utility that we just built
    Finished dev [unoptimized + debuginfo] target(s) in 0.09s
     Running `target/debug/pwd`
/root/learning_rust/linux_tools/pwd

Conclusion 结论

Lib.rs :

pub mod dir_get: This declares a module named dir_get, which can be accessed from other modules.
pub mod dir_get :这声明了一个名为 dir_get 的模块,可以从其他模块访问该模块。

  • use std::env;: This imports the env module from the standard library, which provides functions for interacting with the environment variables of the current process.
    use std::env; :从标准库导入 env 模块,该模块提供与当前进程的环境变量交互的函数。
  • use std::path::PathBuf;: This imports the PathBuf struct from the std::path module, which represents an owned, mutable path.
    use std::path::PathBuf; :这会从 std::path 模块导入 PathBuf 结构,该结构表示拥有的可变路径。

fn get_working_directory() -> std::io::Result<PathBuf>: This defines a function named get_working_directory that returns a result containing a PathBuf representing the current working directory, wrapped in std::io::Result.
fn get_working_directory() -> std::io::Result<PathBuf> :这定义了一个名为 get_working_directory 的函数,该函数返回一个结果,其中包含表示当前工作目录的 PathBuf ,包装在 std::io::Result 中。

  • env::current_dir(): This is a function from the env module that returns a Result<PathBuf, std::io::Error> representing the current working directory.
    env::current_dir() :这是 env 模块中的一个函数,它返回表示当前工作目录的 Result<PathBuf, std::io::Error> 。

pub fn print_working_dir(): This defines a public function named print_working_dir, which takes no arguments.
pub fn print_working_dir() :这定义了一个名为 print_working_dir 的公共函数,它不带任何参数。

  • let result = get_working_directory();: This calls the get_working_directory function and stores the result in the result variable.
    let result = get_working_directory(); :调用 get_working_directory 函数并将结果存储在 result 变量中。
  • match result { ... }: This is a match expression that handles the result of calling get_working_directory(). It matches on the Ok variant, which contains the successfully obtained PathBuf, and the Err variant, which contains an error if the operation failed.
    match result { ... } :这是一个 match 表达式,用于处理调用 get_working_directory() 的结果。它与 Ok 变体(包含成功获取的 PathBuf )和 Err 变体(如果操作失败则包含错误)匹配。
  • Ok(path_buf) => println!("{}", path_buf.as_path().display()),: If get_working_directory() succeeds, this branch is executed, printing the current working directory using path_buf.as_path().display().
    Ok(path_buf) => println!("{}", path_buf.as_path().display()), :如果 get_working_directory() 成功,则执行此分支,并使用 path_buf.as_path().display() 打印当前工作目录。
  • Err(e) => eprintln!("Application Error: {}", e),: If get_working_directory() fails, this branch is executed, printing an error message indicating that an application error occurred.
    Err(e) => eprintln!("Application Error: {}", e), :如果 get_working_directory() 失败,则执行此分支,打印一条错误消息,指示发生应用程序错误。

Main.rs

  • use pwd::dir_get;: This line imports the print_working_dir function from the dir_get module defined in the pwd crate. This allows us to use the function in the current scope.
    use pwd::dir_get; :此行从 pwd 包中定义的 dir_get 模块导入 print_working_dir 函数。这允许我们在当前范围内使用该函数。
  • fn main() { ... }: This defines the main function, which serves as the entry point of the program.
    fn main() { ... } :定义主函数,作为程序的入口点。
  • dir_get::print_working_dir();: This line calls the print_working_dir function from the dir_get module. It is prefixed with dir_get:: to specify that the function is being called from the dir_get module.
    dir_get::print_working_dir(); :此行从 dir_get 模块调用 print_working_dir 函数。它以 dir_get:: 为前缀,以指定从 dir_get 模块调用该函数。
  • The main function does not take any arguments.
    main 函数不接受任何参数。
  • When executed, this program will print the current working directory to the standard output.
    执行时,该程序会将当前工作目录打印到标准输出。
  • The print_working_dir function is defined in the dir_get module and is responsible for obtaining and printing the current working directory.
    print_working_dir 函数定义在 dir_get 模块中,负责获取并打印当前工作目录。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/592682.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

SpringBoot使用AOP注解记录操作日志

一、前言 日志&#xff1a;指系统所指定对象的某些操作和其操作结果按时间有序的集合。 操作日志&#xff1a;主要是对某个对象进行新增操作或者修改操作后记录下这个新增或者修改&#xff0c;操作日志要求可读性比较强。比如张三在某个时间下了订单买了某个商品&#xff01; …

linux实验(数据库备份)

以下所有操作皆以机房电脑上的虚拟机为基础环境 下载链接&#xff1a;Linux课程机房虚拟机# 切换到root用户 su - root安装数据库mysql 5.7 rpm -ivh https://mirrors4.tuna.tsinghua.edu.cn/mysql/yum/mysql-5.7-community-el7-x86_64/mysql-community-common-5.7.29-1.el7.x…

Llama改进之——SwiGLU激活函数

引言 今天介绍LLAMA模型引入的关于激活函数的改进——SwiGLU1&#xff0c;该激活函数取得了不错的效果&#xff0c;得到了广泛地应用。 SwiGLU是GLU的一种变体&#xff0c;其中包含了GLU和Swish激活函数。 GLU GLU(Gated Linear Units,门控线性单元)2引入了两个不同的线性层…

Linux(openEuler、CentOS8)常用的IP修改方式(文本配置工具nmtui+配置文件+nmcli命令)

----本实验环境为openEuler系统<以server方式安装>&#xff08;CentOS类似&#xff0c;可参考本文&#xff09;---- 一、知识点 &#xff08;一&#xff09;文本配置工具nmtui(openEuler已预装) nmtui&#xff08;NetworkManager Text User Interface&#xff09;是一…

ZooKeeper以及DolphinScheduler的用法

目录 一、ZooKeeper的介绍 数据模型 ​编辑 操作使用 ①登录客户端 ​编辑 ②可以查看下面节点有哪些 ③创建新的节点&#xff0c;并指定数据 ④查看节点内的数据 ⑤、删除节点及数据 特殊点&#xff1a; 运行机制&#xff1a; 二、DolphinScheduler的介绍 架构&#…

计算机毕业设计Python+Spark知识图谱高考志愿推荐系统 高考数据分析 高考可视化 高考大数据 大数据毕业设计

毕业设计&#xff08;论文&#xff09;任务书 毕业设计&#xff08;论文&#xff09;题目&#xff1a; 基于大数据的高考志愿推荐系统 设计&#xff08;论文&#xff09;的主要内容与要求&#xff1a; 主要内容&#xff1a; 高…

贝叶斯回归

1. 贝叶斯推断的定义 简单来说&#xff0c;贝叶斯推断 (Bayesian inference) 就是结合“经验 (先验)”和“实践 (样本)”&#xff0c;得出“结论 (后 验)”。 2. 什么是先验&#xff1f; 贝叶斯推断把模型参数看作随机变量。在得到样本之前&#xff0c;根据主观经验和既有知…

巧记英语单词

页面 在输入框中填写英语单词的谐音 这样的话就进行了一次英语单词的记忆练习。 页面代码 <% layout(/layouts/default.html, {title: 英语单词管理, libs: [dataGrid]}){ %> <div class"main-content"><div class"box box-main">&l…

anaconda、cuda、tensorflow、pycharm环境安装

anaconda、cuda、tensorflow、pycharm环境安装 anaconda安装 anaconda官方下载地址 本文使用的是基于python3.9的anaconda 接下来跟着步骤安装&#xff1a; 检验conda是否成功安装 安装CUDA和cuDNN 提醒&#xff0c;CUDA和cuDNN两者必须版本对应&#xff0c;否者将会出错…

my-room-in-3d中的电脑,电视,桌面光带发光原理

1. my-room-in-3d中的电脑&#xff0c;电视&#xff0c;桌面光带发光原理 最近在github中&#xff0c;看到了这样的一个项目&#xff1b; 项目地址 我看到的时候&#xff0c;蛮好奇他这个光带时怎么做的。 最后发现&#xff0c;他是通过&#xff0c;加载一个 lightMap.jpg这个…

大型语言模型的新挑战:AMR语义表示的神秘力量

DeepVisionary 每日深度学习前沿科技推送&顶会论文&数学建模与科技信息前沿资讯分享&#xff0c;与你一起了解前沿科技知识&#xff01; 引言&#xff1a;AMR在大型语言模型中的作用 在自然语言处理&#xff08;NLP&#xff09;的领域中&#xff0c;抽象意义表示&…

查找算法与排序算法

查找算法 二分查找 (要求熟练) // C// 二分查找法&#xff08;递归实现&#xff09; int binarySearch(int *nums, int target, int left, int right) // left代表左边界&#xff0c;right代表右边界 {if (left > right) return -1; // 如果左边大于右边&#xff0c;那么…

esp8266与uno使用软串口通信

esp8266的d6和d5分别与uno的5和6管脚连接&#xff1a; uno程序&#xff1a; //uno #include <SoftwareSerial.h> SoftwareSerial s(5,6);//(RX,TX)void setup(){s.begin(9600);Serial.begin(9600); }void loop(){int data50;if (s.available() > 0) {char c s.read(…

【错题集-编程题】比那名居的桃子(滑动窗口 / 前缀和)

牛客对应题目链接&#xff1a;比那名居的桃子 (nowcoder.com) 一、分析题目 1、滑动窗口 由题意得&#xff0c;我们是要枚举所有大小为 k 的子数组&#xff0c;并且求出这段⼦数组中快乐值和羞耻度之和。因此&#xff0c;可以利用滑动窗口的思想&#xff0c;用两个变量维护大小…

【区块链】共识算法简介

共识算法简介 区块链三要素&#xff1a; 去中心化共识算法智能合约 共识算法作为区块链三大核心技术之一&#xff0c;其重要性不言而喻。今天就来简单介绍共识算法的基本知识。 最简单的解释&#xff0c;共识算法就是要让所有节点达成共识&#xff0c;保证少数服从多数&#x…

从零开始学AI绘画,万字Stable Diffusion终极教程(六)

【第6期】知识补充 欢迎来到SD的终极教程&#xff0c;这是我们的第六节课&#xff0c;也是最后一节课 这套课程分为六节课&#xff0c;会系统性的介绍sd的全部功能&#xff0c;让你打下坚实牢靠的基础 1.SD入门 2.关键词 3.Lora模型 4.图生图 5.controlnet 6.知识补充 …

初识C语言——第九天

ASCII定义 在 C 语言中&#xff0c;每个字符都对应一个 ASCII 码。ASCII 码是一个字符集&#xff0c;它定义了许多常用的字符对应的数字编码。这些编码可以表示为整数&#xff0c;也可以表示为字符类型。在 C 语言中&#xff0c;字符类型被定义为一个整数类型&#xff0c;它占…

C/C++开发,opencv-ml库学习,K近邻(KNN)应用

目录 一、k近邻算法 1.1 算法简介 1.2 opencv-k近邻算法 二、cv::ml::KNearest应用 2.1 数据集样本准备 2.2 KNearest应用 2.3 程序编译 2.4 main.cpp全代码 一、k近邻算法 1.1 算法简介 K近邻算法&#xff08;K-Nearest Neighbor&#xff0c;KNN&#xff09;基本原理是…

Vue按照顺序实现多级弹窗(附Demo)

目录 前言1. 单个弹窗2. 多级弹窗 前言 强化各个知识点&#xff0c;以实战融合&#xff0c;以下两个Demo从实战提取 1. 单个弹窗 部署按钮框以及确定的方法即可 截图如下所示&#xff1a; 以下Demo整体逻辑如下&#xff1a; 点击“生成周月计划”按钮会触发showWeekPlanDia…

FLIR LEPTON3.5 热像仪wifi 科研实验测温采集仪

点击查看详情!点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情点击查看详情 1、描述 这是一款桌面科研实验测温热成像多功能热像记录仪&#xff0c;小巧轻便…
最新文章