If you have already read Accepting command line arguments and Struct Args, let's see how command-line arguments work using a simple calculator as an example.
Add the standard library
use std::env::{args, Args};
Here is the main code
fn main() { let mut arguments: Args = args(); let first_argument = arguments.nth(1).unwrap(); let operator = arguments.nth(0).unwrap().chars().next().unwrap(); let second_argument = arguments.nth(0).unwrap(); let first_number: f64 = first_argument.parse().unwrap(); let second_number = second_argument.parse::<f64>().unwrap(); let result = operate(operator, first_number, second_number); println!("{} {} {} = {}", first_number, operator, second_number, result); }
Function operate() gonna match our operator of type ‘char’
fn operate(operator: char, first_number: f64, second_number: f64) -> f64{ match operator { '+' => first_number + second_number, '-' => first_number - second_number, '/' => first_number / second_number, '*' | 'x' | 'X' => first_number * second_number, => 0.0, } }
Cargorun it with arguments «number operator number» for example:
cargo run 1 + 2
The answer would be look like that:
1 + 2 = 3
Arguments look like that:
{ inner: ["target/debug/calculator", "1", "+", "2"] }
The first element is the path of the executable.
Accessing command line arguments by index
As soon as some of arguments used all previous arguments would be deleted.
let first_argument = arguments.nth(1).unwrap();
Arguments:
{ inner: ["+", "2"] }
So we have to take 0th argument
let operator = arguments.nth(0).unwrap().chars().next().unwrap();
Arguments:
{ inner: ["2"] }
And again wehave to take 0th argument
let second_argument = arguments.nth(0).unwrap();
Arguments:
Args { inner: [] }
That’s why
args.nth(1) = 1 args.nth(0) = + args.nth(0) = 2
Let’s tests it:
#[test] fn add() { assert_eq!(3.0, operate('+', 1.0, 2.0) ); } #[test] fn substruct() { assert_eq!(3.0, operate('-', 5.0, 2.0) ); } #[test] fn multiply() { assert_eq!(4.0, operate('*', 2.0, 2.0) ); assert_eq!(4.0, operate('x', 2.0, 2.0) ); assert_eq!(4.0, operate('X', 2.0, 2.0) ); } #[test] fn divide() { assert_eq!(3.0, operate('/', 6.0, 2.0) ); } #[test] fn error() { assert_ne!(2.0, operate('u', 4.0, 2.0) ); }
Top comments (0)