CodeBlanks Logo Icon CodeBlanks

Command skeleton

Set up basic command reading with args.

Notebook CLI: skeleton

In this project we'll write a command-line notebook: not ekle süt al, not liste, not sil 2, not ara süt. Arguments come from std::env::args(); the first element is the program path:

let args: Vec<String> = std::env::args().collect();
// $ not liste  →  ["not", "liste"]
let komut = args.get(1).map(|s| s.as_str()).unwrap_or("yardim");

To keep the program from crashing when no command is given, we use get(1) and default to yardim. In the exercises we'll pass arguments as a hand-built vector.

Handling arguments as a slice

Putting the command handler in a function taking &[String] makes it testable: main passes the real arguments, tests pass fake ones:

fn komut_adi(args: &[String]) -> &str {
    args.get(1).map(|s| s.as_str()).unwrap_or("yardim")
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    println!("{}", komut_adi(&args));
}

Practice Command name

Write the komut_adi function above. Print the results for two Vec<String>s containing ["not", "liste"] and just ["not"], separated by a space.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn komut_adi(args: &[String]) -> &str {
    args.get(1).map(|s| s.as_str()).unwrap_or("yardim")
}

fn main() {
    let a = vec![String::from("not"), String::from("liste")];
    let b = vec![String::from("not")];
    println!("{} {}", komut_adi(&a), komut_adi(&b));
}

Expected output

liste yardim

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why use <code>args.get(1)</code> instead of <code>args[1]</code>?

  • It's faster
  • args[1] doesn't compile
  • It returns a String
  • If no command is given, you get None instead of a panic Correct answer

Explanation: User input can always be missing; the program should give a friendly help message.

2 Collect the arguments

Question
let args: Vec<String> = std::env::____().collect();
Answer
let args: Vec<String> = std::env::args().collect();

Explanation: std::env::args() yields the program arguments as Strings.

3 Command line and args

Term Meaning
not liste ["not", "liste"]
not ["not"]
not ekle süt ["not", "ekle", "süt"]
args.get(5) None

All lessons in Intermediate