Skip to main content

## ArgGroup

# Struct ArgGroup

Source

    pub struct ArgGroup { /* private fields */ }

Expand description

Specifies a logical group of arguments

You can use this for

- applying validation to an entire group, like `ArgGroup::multiple`
- validate relationships between an argument and a group, like conflicts or requirements
- check which argument in a group was specified on the command-line

For visually grouping arguments in help, see instead `Arg::help_heading`.

## §Examples

The following example demonstrates using an `ArgGroup` to ensure that one, and only one, of the arguments from the specified group is present at runtime.

    let result = Command::new("cmd")
        .arg(arg!(--"set-ver" <ver> "set the version manually"))
        .arg(arg!(--major           "auto increase major"))
        .arg(arg!(--minor           "auto increase minor"))
        .arg(arg!(--patch           "auto increase patch"))
        .group(ArgGroup::new("vers")
             .args(["set-ver", "major", "minor", "patch"])
             .required(true))
        .try_get_matches_from(vec!["cmd", "--major", "--patch"]);
    // Because we used two args in the group it's an error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ArgumentConflict);

This next example shows a passing parse of the same scenario

    let result = Command::new("cmd")
        .arg(arg!(--"set-ver" <ver> "set the version manually"))
        .arg(arg!(--major           "auto increase major"))
        .arg(arg!(--minor           "auto increase minor"))
        .arg(arg!(--patch           "auto increase patch"))
        .group(ArgGroup::new("vers")
             .args(["set-ver", "major", "minor","patch"])
             .required(true))
        .try_get_matches_from(vec!["cmd", "--major"]);
    assert!(result.is_ok());
    let matches = result.unwrap();
    // We may not know which of the args was used, so we can test for the group...
    assert!(matches.contains_id("vers"));
    // We can also ask the group which arg was used
    assert_eq!(matches
        .get_one::<Id>("vers")
        .expect("`vers` is required")
        .as_str(),
        "major"
    );
    // we could also alternatively check each arg individually (not shown here)

## Implementations§

Source§

### impl ArgGroup

#### §Builder

Source

#### pub fn new(id: impl Into<Id>) -> ArgGroup

Create a `ArgGroup` using a unique name.

The name will be used to get values from the group or refer to the group inside of conflict and requirement rules.

##### §Examples

    ArgGroup::new("config")

Source

#### pub fn id(self, id: impl Into<Id>) -> ArgGroup

Sets the group name.

##### §Examples

    ArgGroup::default().id("config")

Source

#### pub fn arg(self, arg_id: impl IntoResettable<Id>) -> ArgGroup

Adds an argument to this group by name

##### §Examples

    let m = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .arg("flag")
            .arg("color"))
        .get_matches_from(vec!["myprog", "-f"]);
    // maybe we don't know which of the two flags was used...
    assert!(m.contains_id("req_flags"));
    // but we can also check individually if needed
    assert!(m.contains_id("flag"));

Source

#### pub fn args(self, ns: impl IntoIterator<Item = impl Into<Id>>) -> ArgGroup

Adds multiple arguments to this group by name

##### §Examples

    let m = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"]))
        .get_matches_from(vec!["myprog", "-f"]);
    // maybe we don't know which of the two flags was used...
    assert!(m.contains_id("req_flags"));
    // but we can also check individually if needed
    assert!(m.contains_id("flag"));

Source

#### pub fn get_args(&self) -> impl Iterator<Item = &Id>

Getters for all args. It will return a vector of `Id`

##### §Example

    let args: Vec<&str> = vec!["a1".into(), "a4".into()];
    let grp = ArgGroup::new("program").args(&args);

    for (pos, arg) in grp.get_args().enumerate() {
        assert_eq!(*arg, args[pos]);
    }

Source

#### pub fn multiple(self, yes: bool) -> ArgGroup

Allows more than one of the `Arg`s in this group to be used. (Default: `false`)

##### §Examples

Notice in this example we use both the `-f` and `-c` flags which are both part of the group

    let m = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"])
            .multiple(true))
        .get_matches_from(vec!["myprog", "-f", "-c"]);
    // maybe we don't know which of the two flags was used...
    assert!(m.contains_id("req_flags"));

In this next example, we show the default behavior (i.e. `multiple(false)`) which will throw an error if more than one of the args in the group was used.

    let result = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"]))
        .try_get_matches_from(vec!["myprog", "-f", "-c"]);
    // Because we used both args in the group it's an error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ArgumentConflict);

Source

#### pub fn is_multiple(&mut self) -> bool

Return true if the group allows more than one of the arguments in this group to be used. (Default: `false`)

##### §Example

    let mut group = ArgGroup::new("myprog")
        .args(["f", "c"])
        .multiple(true);

    assert!(group.is_multiple());

Source

#### pub fn required(self, yes: bool) -> ArgGroup

Require an argument from the group to be present when parsing.

This is unless conflicting with another argument. A required group will be displayed in the usage string of the application in the format `<arg|arg2|arg3>`.

NOTE: This setting only applies to the current `Command` / `Subcommand`s, and not globally.

NOTE: By default, `ArgGroup::multiple` is set to `false` which when combined with `ArgGroup::required(true)` states, “One and only one arg must be used from this group. Use of more than one arg is an error.” Vice setting `ArgGroup::multiple(true)` which states, ’At least one arg from this group must be used. Using multiple is OK.“

##### §Examples

    let result = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"])
            .required(true))
        .try_get_matches_from(vec!["myprog"]);
    // Because we didn't use any of the args in the group, it's an error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);

Source

#### pub fn requires(self, id: impl IntoResettable<Id>) -> ArgGroup

Specify an argument or group that must be present when this group is.

This is not to be confused with a required group. Requirement rules function just like argument requirement rules, you can name other arguments or groups that must be present when any one of the arguments from this group is used.

NOTE: The name provided may be an argument or group name

##### §Examples

    let result = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"])
            .requires("debug"))
        .try_get_matches_from(vec!["myprog", "-c"]);
    // because we used an arg from the group, and the group requires "-d" to be used, it's an
    // error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);

Source

#### pub fn requires_all( self, ns: impl IntoIterator<Item = impl Into<Id>>, ) -> ArgGroup

Specify arguments or groups that must be present when this group is.

This is not to be confused with a required group. Requirement rules function just like argument requirement rules, you can name other arguments or groups that must be present when one of the arguments from this group is used.

NOTE: The names provided may be an argument or group name

##### §Examples

    let result = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("verb")
            .short('v')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"])
            .requires_all(["debug", "verb"]))
        .try_get_matches_from(vec!["myprog", "-c", "-d"]);
    // because we used an arg from the group, and the group requires "-d" and "-v" to be used,
    // yet we only used "-d" it's an error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);

Source

#### pub fn conflicts_with(self, id: impl IntoResettable<Id>) -> ArgGroup

Specify an argument or group that must not be present when this group is.

Exclusion (aka conflict) rules function just like argument exclusion rules, you can name other arguments or groups that must not be present when one of the arguments from this group are used.

NOTE: The name provided may be an argument, or group name

##### §Examples

    let result = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"])
            .conflicts_with("debug"))
        .try_get_matches_from(vec!["myprog", "-c", "-d"]);
    // because we used an arg from the group, and the group conflicts with "-d", it's an error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ArgumentConflict);

Source

#### pub fn conflicts_with_all( self, ns: impl IntoIterator<Item = impl Into<Id>>, ) -> ArgGroup

Specify arguments or groups that must not be present when this group is.

Exclusion rules function just like argument exclusion rules, you can name other arguments or groups that must not be present when one of the arguments from this group are used.

NOTE: The names provided may be an argument, or group name

##### §Examples

    let result = Command::new("myprog")
        .arg(Arg::new("flag")
            .short('f')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("color")
            .short('c')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("debug")
            .short('d')
            .action(ArgAction::SetTrue))
        .arg(Arg::new("verb")
            .short('v')
            .action(ArgAction::SetTrue))
        .group(ArgGroup::new("req_flags")
            .args(["flag", "color"])
            .conflicts_with_all(["debug", "verb"]))
        .try_get_matches_from(vec!["myprog", "-c", "-v"]);
    // because we used an arg from the group, and the group conflicts with either "-v" or "-d"
    // it's an error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert_eq!(err.kind(), ErrorKind::ArgumentConflict);

Source§

### impl ArgGroup

#### §Reflection

Source

#### pub fn get_id(&self) -> &Id

Get the name of the group

Source

#### pub fn is_required_set(&self) -> bool

Reports whether `ArgGroup::required` is set

## Trait Implementations§

Source§

### impl Clone for ArgGroup

Source§

#### fn clone(&self) -> ArgGroup

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

#### fn clone_from(&mut self, source: &Self)

Performs copy-assignment from `source`. Read more
Source§

### impl Debug for ArgGroup

Source§

#### fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

### impl Default for ArgGroup

Source§

#### fn default() -> ArgGroup

Returns the “default value” for a type. Read more
Source§

### impl Eq for ArgGroup

Source§

### impl From<&ArgGroup> for ArgGroup

Source§

#### fn from(g: &ArgGroup) -> ArgGroup

Converts to this type from the input type.
Source§

### impl PartialEq for ArgGroup

Source§

#### fn eq(&self, other: &ArgGroup) -> bool

Equality operator `==`. Read more
1.0.0 (const: unstable) · Source§

#### fn ne(&self, other: &Rhs) -> bool

Inequality operator `!=`. Read more
Source§

### impl StructuralPartialEq for ArgGroup

## Auto Trait Implementations§

§

### impl Freeze for ArgGroup

§

### impl RefUnwindSafe for ArgGroup

§

### impl Send for ArgGroup

§

### impl Sync for ArgGroup

§

### impl Unpin for ArgGroup

§

### impl UnsafeUnpin for ArgGroup

§

### impl UnwindSafe for ArgGroup

## Blanket Implementations§

Source§

### impl<T> Any for T
where T: 'static + ?Sized,

Source§

#### fn type_id(&self) -> TypeId

Gets the `TypeId` of `self`. Read more
Source§

### impl<T> Borrow<T> for T
where T: ?Sized,

Source§

#### fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

### impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

#### fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

### impl<T> CloneToUninit for T
where T: Clone,

Source§

#### unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (`clone_to_uninit`)
Performs copy-assignment from `self` to `dest`. Read more
Source§

### impl<T> From<T> for T

Source§

#### fn from(t: T) -> T

Returns the argument unchanged.

Source§

### impl<T, U> Into<U> for T
where U: From<T>,

Source§

#### fn into(self) -> U

Calls `U::from(self)`.

That is, this conversion is whatever the implementation of `From<T> for U` chooses to do.

Source§

### impl<T> ToOwned for T
where T: Clone,

Source§

#### type Owned = T

The resulting type after obtaining ownership.
Source§

#### fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

#### fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

### impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

#### type Error = Infallible

The type returned in the event of a conversion error.
Source§

#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

### impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

#### type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.