Need help with clap

I am currently self-learning Rust and reading the book Command-line Rust. However, I know that the book I'm reading uses an older version of the clap library. After searching for a while, I found a GitHub repository that uses the latest version of clap.
Can someone explain what is wrong with this code?

use clap::{Command, Arg, ArgAction};

fn main() {
    let matches = Command::new("echor")
        .version("0.1.0")
        .about("Rust Echo")
        .arg(
            Arg::new("text")
                .value_name("TEXT")
                .help("Input Text")
                .required(true)
                .num_args(1..)   
        )
        .arg(
            Arg::new("omit_newline")
                .short('n')
                .action(ArgAction::SetTrue)
                .help("Do not print newline")
        )
        .get_matches();

    let text = matches
        .get_many::<String>("text")
        .unwrap()
        .cloned()
        .collect::<Vec<String>>();

    let omit_newline = matches.get_flag("omit_newline");

    print!("{}{}", text.join(" "), if omit_newline { "" } else { "\n" });
}

However, when I run the code like this:
cargo run -- hello, world
the output on stdout doesn't have a newline.
Can someone explain what is wrong with this code?"

I do know (yet) nothing about clap, but the output of your program looks not wrong too me. Well, this is bash on Linux:

stefan@hx90 /tmp/ttt/src $ cargo run -- --help
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `/tmp/ttt/target/debug/ttt --help`
Rust Echo

Usage: ttt [OPTIONS] <TEXT>...

Arguments:
  <TEXT>...  Input Text

Options:
  -n             Do not print newline
  -h, --help     Print help
  -V, --version  Print version
stefan@hx90 /tmp/ttt/src $ cargo run -- hello, world
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `/tmp/ttt/target/debug/ttt hello, world`
hello, world
stefan@hx90 /tmp/ttt/src $ cargo run -- -n hello, world
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `/tmp/ttt/target/debug/ttt -n hello, world`
hello, worldstefan@hx90 /tmp/ttt/src $ 

Note that the author of "Command Line Rust" announced an updated edition of their book a year ago on Reddit. So, when you recently bought the old edition, you might conatct them, and they might send you at least a recent PDF.

I can't reproduce this, I get a new line. Conversely I don't get a new line if I enable the -n flag.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.