arguments
import std::env::arguments; · source
Command-line arguments read against a declaration of what a program takes: flags, options with values, and positional arguments. An ArgumentParser declares them, parse reads a command line into ParsedArguments, and help_text describes them.
import std::collections::str::{ Str };
import std::collections::string::{ String };
import std::env;
import std::env::arguments::{ ArgumentParser, ParsedArguments };
import std::fmt;
function main() -> i32 {
mut parser: ArgumentParser = ArgumentParser::new("grep");
parser.flag("count", Option::Some('c'), "print only a count")
.option("context", Option::None, "lines", "lines around a match")
.positional("pattern", "what to look for")
.optional_positional("file", "where to look");
const all: Array<String> = env::args();
match (parser.parse(all.as_slice().subslice(1, all.length()))) {
Result::Ok(parsed) => {
const pattern: Str = parsed.value("pattern").unwrap();
const counting: boolean = parsed.flag("count");
fmt::println(f"looking for {pattern}, counting: {counting}");
return 0;
}
Result::Err(error) => {
fmt::eprintln(f"{error}");
const help: String = parser.help_text();
fmt::eprint(f"{help}");
return 2;
}
}
}
An option's value is written --context=3, --context 3, -C3, or -C 3; short flags group, -cv. -- ends the options: every argument after it is positional, even one starting with -. A single - is positional too. A short letter is ASCII.
Types
ArgumentParser
type struct ArgumentParser {
private program: String;
private specifications: Array<ArgumentSpecification>;
}
Each declaring method returns the parser, so declarations chain. A flag is present or not, and counted when repeated. An option takes a value and keeps every value when given more than once. Positional arguments are read in the order they are declared, required ones first: an optional_positional is read after every required one, whatever order they are declared in. parse takes the command line after the program's own name, and the first argument that does not fit the declarations is the error.
Constructors
static new(program: Str) -> ArgumentParser;
static new(program: Str) -> ArgumentParser;A parser that declares nothing yet, for the program named program, the name its help text's usage line shows.
Methods
flag(mut &this, long: Str, short: Option<char>, help: Str) -> mut &ArgumentParser;
flag(mut &this, long: Str, short: Option<char>, help: Str) -> mut &ArgumentParser;A flag, --long or -s: present or not, and counted when repeated.
option(mut &this, long: Str, short: Option<char>, value_name: Str, help: Str) -> mut &ArgumentParser;
option(mut &this, long: Str, short: Option<char>, value_name: Str, help: Str) -> mut &ArgumentParser;An option that takes a value, --long=value, --long value, -svalue or -s value; value_name names the value in the help. Given more than once, it keeps every value, in order.
positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;
positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;A positional argument that must be given. Positional arguments are read in the order they are declared.
optional_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;
optional_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;A positional argument that may be left out. It is read after every required one, whatever order they are declared in.
repeated_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;
repeated_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParser;Any number of positional arguments, none included: every one left after the required and the optional ones, read with values. Only the first one declared receives any.
parse(&this, arguments: &Slice<String>) -> Result<ParsedArguments, ArgumentError>;
parse(&this, arguments: &Slice<String>) -> Result<ParsedArguments, ArgumentError>;Read arguments - the command line after the program's own name - against the declarations. The first argument that does not fit them is the error.
help_text(&this) -> String;
help_text(&this) -> String;A description of the arguments: a usage line, then each positional argument and each flag and option with its help, in the order they were declared.
ParsedArguments
type struct ParsedArguments {
private arguments: Array<ParsedArgument>;
}
Read by the names the arguments were declared under; asking for a name the parser did not declare panics. occurrences counts a repeated flag (-vvv is 3), value is the last value given, and values every one, in order.
Methods
![caller_location]flag(&this, name: Str) -> boolean;
![caller_location]flag(&this, name: Str) -> boolean;True when the flag or option name was given.
![caller_location]occurrences(&this, name: Str) -> i64;
![caller_location]occurrences(&this, name: Str) -> i64;How many times the flag or option name was given: -vvv is 3.
![caller_location]value(&this, name: Str) -> Option<Str>;
![caller_location]value(&this, name: Str) -> Option<Str>;The value of the option or positional argument name: the last one given when the option was given more than once.
![caller_location]values(&this, name: Str) -> &Slice<String>;
![caller_location]values(&this, name: Str) -> &Slice<String>;Every value of the option or repeated positional argument name, in the order they were given.
ArgumentError
type struct ArgumentError with [Eq, Clone, Debug] {
kind: ArgumentErrorKind;
argument: String;
}
The argument a command line went wrong at, as written, and how. For a missing positional argument, argument is its name as the help shows it, <file>. It prints as a one-line message, so a program reports it and then the help text.
Properties
| Property | Type | Notes |
|---|---|---|
kind | ArgumentErrorKind | |
argument | String | The argument as written; for a missing positional argument, its name as the help shows it, <file>. |
Constructors
static new(kind: ArgumentErrorKind, argument: Str) -> ArgumentError;
static new(kind: ArgumentErrorKind, argument: Str) -> ArgumentError;An error of kind at argument, which is copied.
ArgumentErrorKind
type enum ArgumentErrorKind with [Eq, Clone, Debug] {
UnknownOption;
MissingValue;
UnexpectedValue;
MissingPositional;
UnexpectedPositional;
}
Variants
| Variant | Notes |
|---|---|
UnknownOption | An option or short letter nothing declares. |
MissingValue | An option that takes a value came last, with none after it. |
UnexpectedValue | A flag written with a value, --verbose=yes. |
MissingPositional | A required positional argument was not given. |
UnexpectedPositional | More positional arguments than are declared. |
Trait implementations
implement trait Error for struct ArgumentError
implement trait Display for struct ArgumentError
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
type struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
type struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
namespace std::env::arguments;Command-line arguments read against a declaration of what a program takes: flags, options with values, and positional arguments.
module pagetype struct ArgumentParser {}A declaration of the arguments a program takes, which parse reads a command line against and help_text describes. Each declaring method returns the parser, so declarations chain.
type struct ParsedArguments {}The arguments a command line gave, read by the names they were declared under. Asking for a name the parser did not declare panics.
std::env::argumentsfunction name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function main() -> i32mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut parser: ArgumentParserstatic ArgumentParser::new(program: Str) -> ArgumentParserA parser that declares nothing yet, for the program named program, the name its help text's usage line shows.
mut parser: ArgumentParserArgumentParser::flag(mut &this, long: Str, short: Option<char>, help: Str) -> mut &ArgumentParserA flag, --long or -s: present or not, and counted when repeated.
type enum Option<T> with [Eq, Clone, Debug] {
Some(T);
None;
}A value of type T that may be absent: Some(value) or None.
Option::Some(T)ArgumentParser::option(mut &this, long: Str, short: Option<char>, value_name: Str, help: Str) -> mut &ArgumentParserAn option that takes a value, --long=value, --long value, -svalue or -s value; value_name names the value in the help. Given more than once, it keeps every value, in order.
Option::NoneArgumentParser::positional(mut &this, name: Str, help: Str) -> mut &ArgumentParserA positional argument that must be given. Positional arguments are read in the order they are declared.
std::env::argumentsArgumentParser::optional_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParserA positional argument that may be left out. It is read after every required one, whatever order they are declared in.
std::env::argumentsconst name: Type = value;An immutable binding: it cannot be reassigned after initialisation. The annotation may be omitted when an initialiser is present - the binding takes the initialiser's concrete type, inferred locally. Mutability is opt-in through mut.
const all: Array<String>type struct Array<T, A = GlobalAllocator> where A: Allocator {}A growable sequence of Ts stored contiguously, owning its elements; A is the allocator its storage comes from. Indexing out of range panics; get answers None instead.
function args() -> Array<String>Program arguments as UTF-8 strings. The first element is the program name. On Windows the runtime splits the wide command line before main runs and transcodes it, so non-ASCII arguments arrive intact and a lone surrogate in one reads as U+FFFD. Returns an empty array if the runtime hasn't published argv yet.
match (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, constants, and tuple and destructuring patterns, such as (0, 1..8) or Option::Some((count, _)), and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
ArgumentParser::parse(&this, arguments: &Slice<String>) -> Result<ParsedArguments, ArgumentError>Read arguments - the command line after the program's own name - against the declarations. The first argument that does not fit them is the error.
const all: Array<String>Slice::subslice(&this, start: i64, end: i64) -> &Slice<T>The sub-slice [start, end), to read. Panics if start is negative, start > end, or end > length.
type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
Result::Ok(T)parsed: ParsedArgumentspattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
const pattern: Strparsed: ParsedArgumentsParsedArguments::value(&this, name: Str) -> Option<Str>The value of the option or positional argument name: the last one given when the option was given more than once.
Option::unwrap(this) -> TReturn the inner value, aborting on None. Prefer unwrap_or or a match in code that must not panic. Consumes the option: the value moves out to the caller.
const counting: booleanParsedArguments::flag(&this, name: Str) -> booleanTrue when the flag or option name was given.
const pattern: Strconst counting: booleanreturn value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
Result::Err(E)error: ArgumentErrorerror: ArgumentErrorconst help: StringArgumentParser::help_text(&this) -> StringA description of the arguments: a usage line, then each positional argument and each flag and option with its help, in the order they were declared.
std::env::argumentsfunction eprint(text: Arguments) -> voidWrite text to stderr, as print writes it to stdout: an f-string, a literal or a Str, nothing consumed. Display-based counterpart to eprintf.
const help: Stringtype struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct ArgumentParser {}A declaration of the arguments a program takes, which parse reads a command line against and help_text describes. Each declaring method returns the parser, so declarations chain.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
ArgumentParser.program: StringArgumentParser.specifications: Array<ArgumentSpecification>type struct ParsedArguments {}The arguments a command line gave, read by the names they were declared under. Asking for a name the parser did not declare panics.
ParsedArguments.arguments: Array<ParsedArgument>type struct ArgumentError with [Eq, Clone, Debug] {
kind: ArgumentErrorKind;
argument: String;
}The argument a command line went wrong at, and how.
type struct Point with [Eq, Clone, Debug] { .. }Asks the compiler to generate implementations of the listed traits for the type, each working through its fields or variants in declaration order. The derivable traits are Eq, Ord, Hash, Clone, Debug, Default, ToValue and FromValue, and the text formats' FromJson, ToJson, FromYaml, ToYaml, FromToml and ToToml. The clause comes after the name and its parameters, before where.
type trait Eq<Rhs = This> {
equals(&this, other: &Rhs) -> boolean;
}Types that support value equality with a value of Rhs, which is the type itself unless an implementation names another: implement trait Eq for Str compares two Strs, and implement trait Eq<string> for Str a Str with a string.
type trait Clone {
clone(&this) -> This;
}A type whose values can be duplicated into independent copies. A type takes it with with [Clone] on its declaration, or by implementing clone by hand.
type trait Debug {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
}How a value reads to a programmer: what {x:?} writes, and {x:#?} over several lines. with [Debug] on a declaration writes it field by field.
ArgumentError.kind: ArgumentErrorKindtype enum ArgumentErrorKind with [Eq, Clone, Debug] {
UnknownOption;
MissingValue;
UnexpectedValue;
MissingPositional;
UnexpectedPositional;
}Why a command line did not fit the declarations.
std::env::argumentsArgumentError.argument: StringThe argument as written; for a missing positional argument, its name as the help shows it, <file>.
type enum Name {
Unit,
Payload(T),
Named { x: i32 },
}An algebraic data type. Variants may be bare or carry a tuple or struct payload, and a match on an enum must cover every variant. Name::Variant names a variant; methods are added with implement enum Name { ... }.
type enum ArgumentErrorKind with [Eq, Clone, Debug] {
UnknownOption;
MissingValue;
UnexpectedValue;
MissingPositional;
UnexpectedPositional;
}Why a command line did not fit the declarations.
ArgumentErrorKind::UnknownOptionAn option or short letter nothing declares.
ArgumentErrorKind::MissingValueAn option that takes a value came last, with none after it.
ArgumentErrorKind::UnexpectedValueA flag written with a value, --verbose=yes.
ArgumentErrorKind::MissingPositionalA required positional argument was not given.
ArgumentErrorKind::UnexpectedPositionalMore positional arguments than are declared.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static ArgumentError::new(kind: ArgumentErrorKind, argument: Str) -> ArgumentErrorAn error of kind at argument, which is copied.
(parameter) program: Strmut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
(parameter) long: Str(parameter) short: Option<char>(parameter) help: Str(parameter) value_name: Str(parameter) name: StrArgumentParser::repeated_positional(mut &this, name: Str, help: Str) -> mut &ArgumentParserAny number of positional arguments, none included: every one left after the required and the optional ones, read with values. Only the first one declared receives any.
ParsedArguments::values(&this, name: Str) -> &Slice<String>Every value of the option or repeated positional argument name, in the order they were given.
(parameter) arguments: &Slice<String>type struct Slice<T> {}The elements are reached through ptr, declared read-only: through a mut &Slice<T> it reads as a writable pointer, through a &Slice<T> as the read-only one it is.
type struct ArgumentError with [Eq, Clone, Debug] {
kind: ArgumentErrorKind;
argument: String;
}The argument a command line went wrong at, and how.
std::env::argumentsParsedArguments::occurrences(&this, name: Str) -> i64How many times the flag or option name was given: -vvv is 3.
ArgumentError.argument: StringThe argument as written; for a missing positional argument, its name as the help shows it, <file>.
ArgumentError.kind: ArgumentErrorKind(parameter) kind: ArgumentErrorKind(parameter) argument: StrArgumentErrorKind::MissingValueAn option that takes a value came last, with none after it.
std::env::argumentsArgumentErrorKind::MissingPositionalA required positional argument was not given.
std::env::argumentsArgumentErrorKind::UnexpectedPositionalMore positional arguments than are declared.
std::env::argumentsimplement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement trait Trait for Type { ... }Introduces a trait implementation: the block supplies, for one concrete type, the method bodies the trait requires.
language referencetype trait Error : Display, Debug {
source(&this) -> Option<virtual &Error>;
}An error: a message for a person through Display, a fuller form through Debug, and the error it was caused by, if it keeps one.
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype trait Display {
fmt(&this, f: mut &Formatter) -> Result<(), FormatError>;
to_string(&this) -> String;
}How a value reads to a person: what {x} in an f-string and println write. Implement it for a type a user sees.