我试图先设置一个String默认值,但String如果给出了一个命令行参数,则更新它...
这是我的起点(不编译):
use std::env;
fn main() {
let mut config_file = "C:\\temp\\rust\\config.txt".to_string();
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
config_file = args[1];
}
println!("Config file path: {}", config_file);
}
Run Code Online (Sandbox Code Playgroud)
所以,(我认为)env::args()给了我一个拥有的矢量或拥有的字符串......我怎么做:
注意:
$ rustc --version
rustc 1.8.0 (db2939409 2016-04-11)
Run Code Online (Sandbox Code Playgroud)
在Rust中,要创建元素的副本,它应该实现Clone特征,因此有一个.clone()方法.
String实现Clone,因此:
config_file = args[1].clone();
Run Code Online (Sandbox Code Playgroud)
但是,您的方法有许多不必要的内存分配; 我们可以做得更好,没有必要创建一个Vec,args()产生一个迭代器,所以让我们直接使用它,并选择有趣的值.
考虑到这一点:
fn main() {
let mut config_file = "C:\\temp\\rust\\config.txt".to_string();
if let Some(v) = env::args().nth(1) {
config_file = v;
}
println!("Config file path: {}", config_file);
}
Run Code Online (Sandbox Code Playgroud)
在Shepmaster的要求下:这是表演时间!
以下是一个等效的程序,没有可变性或转义字符,并且分配尽可能少:
fn main() {
let config_file = env::args()
.nth(1)
.unwrap_or_else(|| r#"C:\temp\rust\config.txt"#.to_string());
println!("Config file path: {}", config_file);
}
Run Code Online (Sandbox Code Playgroud)
它使用unwrap_or_else的Option由归国nth(1)得到的任何内容Option,或者,如果没有使用过的λ产生的值.
它还显示了Raw String Literals的情况,这是在字符串中嵌入斜杠时使用的一个很棒的功能.