0Pricing
Learn Rust Coding · 강의

clap 기초

인수 구문 분석

clap 기초은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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.

자주 묻는 질문

“clap 기초” 강의는 무료인가요?

네 — “clap 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“clap 기초”에서 뭘 배우나요?

인수 구문 분석 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“clap 기초” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. clap 기초
  2. 하위 명령
  3. Derive API
  4. 검증과 도움말
← Learn Rust Coding(으)로 돌아가기