官术网_书友最值得收藏!

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 266字
  • 2021-07-02 23:07:22

Command-line arguments

When a program is started, it can be started with or without arguments. These arguments are normally fed in as parameters when the program is called. A simple example of this is starting the manual application (found on many BSD and Linux machines):

man ffmpeg 

In the preceding statement, man is the name of the program or script to be called with the argument ffmpeg. Similarly, take a look at the following example for Windows users:

Notepad is the program name with the first argument being the file to read in (in this example, the file doesn't exist, so the UI asks if you wish to create it).

It is not uncommon for one program to load another program to perform a task.

In C, the parameter list for main is given as follows:

int main(int argc, char *argv[])

argc is the maximum number of arguments with argv holding the arguments. Here, the program name is argv[0], so all additional arguments start at 1.

Rust's main takes no arguments like this. Command-line parameters are available through the standard library std::env::args (environment arguments). For simplicity, it is convenient to store the arguments in Vec<String>, because env::args returns an iterator that yields a String.

No parameters are passed into main directly:

// 03/args/src/main.rs
use std::env; fn main() { let args: Vec<String> = env::args().collect(); println!("There was {:?} arguments passed in. They were {:?}.", args.len() - 1, &args[1..]); }

The collect method converts the iterator into a vector, making it possible to access it by indexing. Without it, we would have to go through the arguments one by one.

主站蜘蛛池模板: 桃源县| 格尔木市| 晋州市| 百色市| 会昌县| 泰和县| 新巴尔虎左旗| 邵武市| 马鞍山市| 泰州市| 宁晋县| 云霄县| 色达县| 襄城县| 高碑店市| 怀仁县| 边坝县| 无棣县| 慈溪市| 长岭县| 邻水| 河津市| 浪卡子县| 黄浦区| 从江县| 迁西县| 闽清县| 兴宁市| 张家川| 荆门市| 英德市| 宽甸| 萝北县| 舞钢市| 松江区| 怀远县| 荣成市| 锦屏县| 十堰市| 安溪县| 石狮市|