0Pricing
Learn Rust Coding · Lección

Fundamentos de clap

Análisis de argumentos

Fundamentos de clap es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why clap?

clap (Command Line Argument Parser) is the de-facto standard crate for building CLIs in Rust.

  • Parses arguments, flags, and options
  • Generates --help and --version automatically
  • Validates input and reports friendly errors

Without it you would manually iterate over std::env::args() and handle every edge case yourself.

Reading args by hand

Before reaching for clap, it helps to see the raw approach. std::env::args() yields an iterator where the first item is the program name.

fn main() {
    let args: Vec<String> = std::env::args().collect();
    println!("Program: {}", args[0]);
    println!("Got {} extra arg(s)", args.len() - 1);
}

Adding clap to Cargo.toml

To use clap you declare it as a dependency. The derive feature unlocks the macro-based API.

  • cargo add clap --features derive

This step runs in your terminal and edits your project files, so it is not something we execute here.

[dependencies]
clap = { version = "4", features = ["derive"] }

The builder API

clap has two styles. The builder API constructs a Command at runtime by chaining method calls.

use clap::{Command, Arg};

fn main() {
    let cmd = Command::new("greet")
        .arg(Arg::new("name"));
    let matches = cmd.get_matches();
    // access values from matches
}

Positional arguments

A positional argument is supplied by order, not by a flag. Here name is read directly from the command line.

  • greet Alice sets name to Alice
use clap::{Command, Arg};

fn main() {
    let m = Command::new("greet")
        .arg(Arg::new("name").required(true))
        .get_matches();
    let name = m.get_one::<String>("name").unwrap();
    println!("Hello, {}!", name);
}

Optional flags

A flag is a boolean switch. Use ArgAction::SetTrue so its presence flips a bool.

  • --loud turns the flag on
use clap::{Command, Arg, ArgAction};

fn main() {
    let m = Command::new("greet")
        .arg(Arg::new("loud").long("loud").action(ArgAction::SetTrue))
        .get_matches();
    let loud = m.get_flag("loud");
    println!("loud = {}", loud);
}

Options with values

An option takes a value, like --count 3. Give it a short and a long name for ergonomics.

use clap::{Command, Arg};

fn main() {
    let m = Command::new("greet")
        .arg(Arg::new("count").short('c').long("count"))
        .get_matches();
    if let Some(c) = m.get_one::<String>("count") {
        println!("count = {}", c);
    }
}

Default values

Give an argument a fallback with default_value so users can omit it.

  • If --count is missing, it becomes 1
use clap::{Command, Arg};

fn main() {
    let m = Command::new("greet")
        .arg(Arg::new("count").long("count").default_value("1"))
        .get_matches();
    let count = m.get_one::<String>("count").unwrap();
    println!("count = {}", count);
}

Simulating the result

Even without clap installed we can model what the parsed values look like. Here is a plain-Rust stand-in showing the logic clap performs for us.

fn main() {
    let name = "Alice";
    let count: u32 = 3;
    for _ in 0..count {
        println!("Hello, {}!", name);
    }
}

Auto-generated help

clap builds --help for free from your argument metadata. Add about and help strings to make it useful.

use clap::{Command, Arg};

fn main() {
    Command::new("greet")
        .about("Greets a person")
        .arg(Arg::new("name").help("Who to greet"))
        .get_matches();
}

Version flag

Set a version once and clap wires up --version. The crate_version! macro pulls it from Cargo.toml.

use clap::Command;

fn main() {
    Command::new("greet")
        .version("1.0.0")
        .get_matches();
}

Quick Check

Test your understanding of clap basics.

Recap

You learned the foundations of clap:

  • Add it with the derive feature
  • The builder API uses Command and Arg
  • Positionals are ordered; flags use SetTrue; options take values
  • default_value provides fallbacks
  • --help and --version are generated automatically

Next you will structure larger CLIs with subcommands.

Preguntas frecuentes

¿La lección «Fundamentos de clap» es gratis?

Sí — el texto completo de «Fundamentos de clap» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.

¿Qué aprenderé en «Fundamentos de clap»?

Análisis de argumentos Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Fundamentos de clap»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Fundamentos de clap
  2. Subcomandos
  3. API derive
  4. Validación y ayuda
← Volver a Learn Rust Coding