从命令行读取参数

use std::env;

fn main() {
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
}
ai@aisty:/opt/wks/rust/rfil/rcmd/target/debug$ ./rcmd aa bb cc
["./rcmd", "aa", "bb", "cc"]

第一个参数是命令本身

The args Function and Invalid Unicode

Note that std::env::args will panic if any argument contains invalid Unicode. If your program needs to accept arguments containing invalid Unicode, use std::env::args_os instead. That function returns an iterator that produces OsString values instead of String values. We’ve chosen to use std::env::args here for simplicity, because OsString values differ per platform and are more complex to work with than String values.

索引为0的参数是命令本身,从索引为1的参数开始才是输入的参数

use std::env;

fn main() {
let args: Vec<String> = env::args().collect(); let query = &args[1];
let filename = &args[2]; println!("Searching for {}", query);
println!("In file {}", filename);
}
ai@aisty:/opt/wks/rust/rfil/rcmd$ cargo run name /tmp/aa.txt
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/rcmd name /tmp/aa.txt`
Searching for name
In file /tmp/aa.txt

读取指定的文件内容

use std::env;
use std::fs; fn main() {
let args: Vec<String> = env::args().collect(); let filename = &args[1];
println!("In file {}", filename); let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file"); println!("With text:\n{}", contents); }
ai@aisty:/opt/wks/rust/rfil/rcmd$ cargo run /tmp/aa.txt
Compiling rcmd v0.1.0 (/opt/wks/rust/rfil/rcmd)
Finished dev [unoptimized + debuginfo] target(s) in 0.21s
Running `target/debug/rcmd /tmp/aa.txt`
In file /tmp/aa.txt
With text:
aa
use std::env;
use std::fs; fn main() {
let args: Vec<String> = env::args().collect(); let (query, filename) = parse_config(&args); // --snip-- println!("Searching for {}", query);
println!("In file {}", filename); let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file"); println!("With text:\n{}", contents);
} fn parse_config(args: &[String]) -> (&str, &str) {
let query = &args[1];
let filename = &args[2]; (query, filename)
}
ai@aisty:/opt/wks/rust/rfil/rcmd$ cargo run aa /tmp/aa.log
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/rcmd aa /tmp/aa.log`
Searching for aa
In file /tmp/aa.log
With text:
aa
bb
use std::env;
use std::fs; fn main() {
let args: Vec<String> = env::args().collect(); let config = parse_config(&args); println!("Searching for {}", config.query);
println!("In file {}", config.filename); let contents = fs::read_to_string(config.filename)
.expect("Something went wrong reading the file"); println!("With text:\n{}", contents);
} struct Config {
query: String,
filename: String,
} fn parse_config(args: &[String]) -> Config {
let query = args[1].clone();
let filename = args[2].clone(); Config { query, filename }
}

clone性能不好,后面会介绍其他方式

There’s a tendency among many Rustaceans to avoid using clone to fix ownership problems because of its runtime cost.

use std::env;
use std::fs; fn main() {
let args: Vec<String> = env::args().collect(); let config = Config::new(&args); println!("Searching for {}", config.query);
println!("In file {}", config.filename); let contents = fs::read_to_string(config.filename)
.expect("Something went wrong reading the file"); println!("With text:\n{}", contents); } struct Config {
query: String,
filename: String,
} impl Config {
fn new(args: &[String]) -> Config {
let query = args[1].clone();
let filename = args[2].clone(); Config { query, filename }
}
}

添加自定义错误

use std::env;
use std::fs; fn main() {
let args: Vec<String> = env::args().collect(); let config = Config::new(&args); println!("Searching for {}", config.query);
println!("In file {}", config.filename); let contents = fs::read_to_string(config.filename)
.expect("Something went wrong reading the file"); println!("With text:\n{}", contents); } struct Config {
query: String,
filename: String,
} impl Config {
fn new(args: &[String]) -> Config {
if args.len() < 3 {
panic!("not enough arguments");
} let query = args[1].clone();
let filename = args[2].clone(); Config { query, filename }
}
}

Returning a Result from new Instead of Calling panic!

4.2 rust 命令行参数的更多相关文章

  1. python处理命令行参数

    直接从命令行执行py文件的时候如果带有参数,如何获取这些参数,如何解析? http://blog.chinaunix.net/uid-20786165-id-3182268.html sys.argv ...

  2. .NET Core采用的全新配置系统[5]: 聊聊默认支持的各种配置源[内存变量,环境变量和命令行参数]

    较之传统通过App.config和Web.config这两个XML文件承载的配置系统,.NET Core采用的这个全新的配置模型的最大一个优势就是针对多种不同配置源的支持.我们可以将内存变量.命令行参 ...

  3. Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数

    特殊变量列表 变量 含义 $0 当前脚本的文件名 $n 传递给脚本或函数的参数.n 是一个数字,表示第几个参数.例如,第一个参数是$1,第二个参数是$2. $# 传递给脚本或函数的参数个数. $* 传 ...

  4. powershell脚本,命令行参数传值,并绑定变量的例子

    这是小技巧文章,所以文章不长.但原创唯一,非常重要.我搜了下,还真没有人发 powershell怎样 [命令行 参数 绑定],所以我决定写成博客. 搜索关键字如下: powershell 命令行 参数 ...

  5. VS2013 带命令行参数的调试问题 解决方案

    int main(int argc,char* argv[]) argc是命令行总的参数个数,argv[]是argc个参数,其中第0个参数是程序的全名,以后的参数命令行后面跟的用户输入的参数 比如:  ...

  6. 使用getopt()处理命令行参数

    假设有一程序 testopt,其命令行选项参数有: -i            选项 -l            选项 -r           选项 -n <值> 带关联值的选项 则处理 ...

  7. 7z命令行参数中的路径

    最近在自动化的过程中用到了7z命令行工具,发现其参数中的路径挺有意思的,在此总结一下.本文中所有demo使用的7z版本为:15.14 x64. 压缩某个文件夹 下面的命令会把g:\temp\目录和目录 ...

  8. [转]Python 命令行参数和getopt模块详解

    FROM : http://www.tuicool.com/articles/jaqQvq 有时候我们需要写一些脚本处理一些任务,这时候往往需要提供一些命令行参数,根据不同参数进行不同的处理,在Pyt ...

  9. 你可能不知道的Google Chrome命令行参数

    概述:              关于Google Chrome命令行参数(英文叫Google Chrome Command line switches),是Chrome为了实现实验性功能.方便调试. ...

随机推荐

  1. 小白都能看懂的Spring源码揭秘之IOC容器源码分析

    目录 前言 IOC 只是一个 Map 集合 IOC 三大核心接口 IOC 初始化三大步骤 定位 加载 注册 总结 前言 在 Spring 框架中,大家耳熟能详的无非就是 IOC,DI,Spring M ...

  2. ELK集群之filebeat(6)

    filebeat工作原理 ilebeat是本地文件的日志数据采集器. 作为服务器上的代理安装,Filebeat监视日志目录或特定日志文件,tail file,并将它们转发给Elasticsearch或 ...

  3. 网页视频不能自动播放?HTML5 video报错Uncaught (in promise) DOMException解决方法

    话说发哥四年前写了一个网页,如上图效果,实际网址http://pano.z01.com ,话说做好时是正常的,突然某一天,客户说你这个网站动画不见了,这是什么原因? 结果检查脚本一切正常. 其实也不是 ...

  4. Android——ViewHolder的作用与用法

    转载至:https://www.cnblogs.com/wugu-ren/p/6106379.htmlViewHolder通常出现在适配器里,为的是listview滚动的时候快速设置值,而不必每次都重 ...

  5. 退出cmd命令

    中断cmd正在执行的任务:按 Ctrl+C退出cmd:exit最好不要直接关闭,而是用Ctrl+C中断任务后在关闭,以免造成程序运行异常.

  6. Linux——搭建Apache(httpd)服务器

    一.基本概念 Apache(或httpd)是Internet上使用最多的Web服务器技术之一,使用的传输协议是http超文本传输协议(一个基于超文本的协议),用于通过网络连接来发送和接受对象. 有两个 ...

  7. [loj3278]收获

    人的移动之间会相互影响,因此不妨看成果树逆时针移动,显然果树之间独立 考虑建图:1.每一棵果树向其逆时针旋转后第一个人连边:2.每一个人向其逆时针旋转不小于$C$的第一个人连边(即下一个摘的人),边权 ...

  8. [cf643G]Choosing Ads

    首先对于$p>50$,有经典的做法,即不断删去区间中不同的两数,最终剩下的即为出现次数超过一半的数(或没有),用线段树维护即可 那么对于$p\le 50$,类似的,即删去区间中不同的$\lflo ...

  9. [nowcoder5668I]Sorting the Array

    令$f(n,b,m)=a[1..n]$(这里下标从1开始),考虑一些性质: 性质1.对于$\forall 1\le i\le n-m+1$,若$\exists 1\le j<i,a[j]> ...

  10. 「后端小伙伴来学前端了」Vuex进阶操作,让你的代码更加高效(简称如何学会偷懒 【手动狗头】)

    学妹手机里的美照 前言 前一篇写了Vuex基本使用,用起来还稍稍有些繁琐,代码有很多 冗余的地方,这篇就带着大家用更简单的方式来使用Vuex(其实就是怎么更好的偷懒,用更少的代码来完之前的事情) 进入 ...