Precisely initializing a row vector

I am trying to create a vector Stringto check arg parsing (as this is what returns std::env::args()), but struggling with how to do it briefly.

What I want:

let test_args = vec!["-w", "60", "arg"]; // should array of Strings
let expected_results = my_arg_parser(test_args);

This clearly does not work, because the contents of the vectors are all &strs.

Usage String::from, but works, but does not scale well and ugly :)

let args = vec![String::from("-w"), String::from("60"), String::from("args")];

I could match the links and return the string objects, but that looks a lot:

let args = vec!["-w", "60", "args"].iter().map(|x| x.to_string()).collect::<Vec<String>>();

Should I just create a helper function for the conversion, or is there an easier way?

+4
source share
3 answers

You can use the method to_string()directly in literals:

let test_args = vec!["-w".to_string(), "60".to_string(), "arg".to_string()];

Otherwise, the macro for this will be simple as:

macro_rules! vec_of_strings {
    ($($x:expr),*) => (vec![$($x.to_string()),*]);
}

. play.rust.org

+5

JDemler . , :

-, into() to_string() , . to_string()/String::from(). :

vec!["a".to_string(), "b".into(), "c".into()];

-, . , String, env::args(). , :

fn parse_args(args: &[String]) -> SomeResult { ... }

, String, AsRef<str>. :

fn parse_args<T: AsRef<str>>(args: &[T]) -> SomeResult { ... }

, String, str . &[String] &[&str] . , ??


, , String, <T: Into<String>>, String, &str, Cow. .

: CLI-Arg (clap-rs, docopt-rs,...), .

+4

, Lukas Kalbertodt answer - , , .

map:

  • .
  • No need to use the full type ( Vec<String>); you can only specify a collection ( Vec<_>). If you pass the result to a function that only accepts Vec<String>, then you do not need any explicit types at all; it can be fully withdrawn.
  • You can use a little shorter s.into()in map.

fn do_stuff_with_args(args: Vec<String>) { println!("{}", args.len()) }

fn main() {
    let args = ["-w", "60", "args"].iter().map(|&s| s.into()).collect();
    do_stuff_with_args(args);
}
+4
source

All Articles