Need help with clap

⚓ Rust    📅 2025-07-09    👤 surdeus    👁️ 2      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: 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?"

1 post - 1 participant

Read full topic

🏷️ rust_feed