Skip to content

Chapter 2 "echor": breaking changes in clap 3 & 4 need adjustment #13

@UweSauter

Description

@UweSauter

For everyone trying to follow along using a current (4.2.7) version of clap here's a working solution:

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

fn main() {
    let matches = Command::new("echor")
        .version("0.1.0")
        .author("author")
        .about("echo in Rust")
        .arg(
            Arg::new("text")
                .value_name("TEXT")
                .help("input text")
                .required(true)
                .action(ArgAction::Append),
        )
        .arg(
            Arg::new("omit newline")
                .short('n')
                .help("Don't print newline character")
                .action(ArgAction::SetTrue),
        )
        .get_matches();
    let text: Vec<&str> = matches
        .get_many("text")
        .unwrap()
        .map(String::as_str)
        .collect();
    let omit_newline = matches.get_flag("omit newline");
    let ending = if omit_newline { "" } else { "\n" };
    print!("{}{}", text.join(" "), ending);
}

There have been some breaking changes in clap since 2.33 that required some work to get right. Most challenging was to collect the arguments into text.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions