pub struct Getopt {
pub optind: usize,
pub optopt: char,
pub optarg: Option<String>,
pub opterr: bool,
/* private fields */
}Expand description
A BSD-style command-line option parser.
Getopt iterates over command-line arguments and returns options one by one,
mimicking the behavior of traditional Unix getopt.
The parser maintains internal state such as:
optind: index of the next argument to processoptarg: argument associated with the current option (if any)optopt: the last option character processedopterr: whether to print error messages
§Example
use bsd_getopt::Getopt;
let args = vec![
"prog".to_string(),
"-a".to_string(),
"-bvalue".to_string(),
];
let mut g = Getopt::new("ab:", args);
assert_eq!(g.next(), Some('a'));
assert_eq!(g.next(), Some('b'));
assert_eq!(g.optarg, Some("value".to_string()));
assert_eq!(g.next(), None);Fields§
§optind: usize§optopt: char§optarg: Option<String>§opterr: boolImplementations§
Source§impl Getopt
impl Getopt
Sourcepub fn new(optstring: &str, args: Vec<String>) -> Self
pub fn new(optstring: &str, args: Vec<String>) -> Self
Creates a new Getopt parser.
§Parameters
optstring: A string describing valid options.args: Command-line arguments (typically fromstd::env::args()).
§Behavior
- Parsing starts from index 1 (skipping program name)
- Internal state is initialized to default values
§Example
use bsd_getopt::Getopt;
let args = vec!["prog".to_string(), "-a".to_string()];
let parser = Getopt::new("a", args);Sourcepub fn next(&mut self) -> Option<char>
pub fn next(&mut self) -> Option<char>
Returns the next option character, or None if parsing is complete.
This function mimics the behavior of the standard getopt:
- Returns
Some(char)for a valid option - Returns
Some('?')for an unknown option - Returns
Some(':')if an argument is missing andoptstringstarts with: - Returns
Nonewhen no more options are available
§Side Effects
- Updates
optind,optarg, andoptopt - May print errors to stderr if
opterristrue
§Rules
- Options can be grouped:
-abc - Options with arguments:
-o value-ovalue
--stops option parsing
§Example
use bsd_getopt::Getopt;
let args = vec![
"prog".to_string(),
"-a".to_string(),
"-b".to_string(),
"foo".to_string(),
];
let mut g = Getopt::new("ab:", args);
assert_eq!(g.next(), Some('a'));
assert_eq!(g.next(), Some('b'));
assert_eq!(g.optarg, Some("foo".to_string()));
assert_eq!(g.next(), None);Trait Implementations§
Auto Trait Implementations§
impl Freeze for Getopt
impl RefUnwindSafe for Getopt
impl Send for Getopt
impl Sync for Getopt
impl Unpin for Getopt
impl UnsafeUnpin for Getopt
impl UnwindSafe for Getopt
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more