Stage 2.9: Reading Command Line Arguments
This one is a bit more difficult, but you will learn the used parts in later lessons.
This should you just give an example of how do you read arguments from the command line.
In programminging languages like C# or Java you always have to define a parameter
for it, e. g. String args[]
In Rust this is not needed. To read arguments from the command line, you have to import the
module std::env
to collect arguments.
this is done by writing use std::env;
. After it, you can use env
in your
file.
With let args: Vec<String> = env::args().collect();
your program will read all
arguments in a dynamic String array, called Vector. This is similar to Java's parameter (String args[])
Vectors will be covered in a later section.
Since this is a Vector
we can't simply print it as a string. Therefore we have to
add :?
to the curly braces.
Formatting will be covered in a later section, don't worry.
You can test it locally by creating a project with cargo new hello-arguments
,
adding the code from the Rust Playground and then call it with
cargo run hello world
Then you should see the output: Your arguments are ["target\\debug\\hello-arguments.exe", "hello", "world"]
Further information: