4.2 rust 命令行参数

 从命令行读取参数

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.

 

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 

 

上一篇:抽奖


下一篇:C# 应该没有类似 C++ 的 const 形参