Alexander Zhak
Alexander Zhak

Reputation: 9272

StructOpt: how to combine all arguments in a single string?

What I want to do is to access user-provided command-line arguments as a single string. First, I did this as:

let lst: Vec<String> = std::env::args().collect();
let res: String = lst[1..].join(" ");

But then I decided to try doing it with structopt and got stuck. Is it possible to achieve desired result with structopt and how should I do it?

Upvotes: 4

Views: 946

Answers (1)

Đorđe Zeljić
Đorđe Zeljić

Reputation: 1825

Here is simple example:

extern crate structopt; // 0.3.11

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "arguments")]
struct Arguments {
    #[structopt(name = "ARGUMENTS")]
    rest: Vec<String>
}

impl Arguments {
    fn get_joined(&self, separator: &str) -> String {
        self.rest.join(separator)
    }
}

fn main() {
    let arguments = Arguments::from_args();

    println!("{}", arguments.get_joined(" "));
}

If you just need to join arguments to string, your approach is already good. I suppose you want to use structopt because you want to read other command line arguments. In that case, just extend struct to support key=value pairs. For example:

extern crate structopt; // 0.3.11

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "arguments")]
struct Arguments {
    #[structopt(short, long)]
    debug: bool,

    #[structopt(short = "v", long = "velocity", default_value = "42")]
    speed: f64,

    #[structopt(name = "ARGUMENTS")]
    rest: Vec<String>
}

impl Arguments {
    fn get_joined(&self, separator: &str) -> String {
        self.rest.join(separator)
    }
}

fn main() {
    let arguments = Arguments::from_args();

    println!("{}", arguments.get_joined(" "));

    println!("{:?}", arguments);
}

Call should looks like: ./target/release/try-structopt --debug -v 9.81 who am i

And the output is:

who am i

Arguments { debug: true, speed: 9.81, rest: ["who", "am", "i"] }

Upvotes: 3

Related Questions