What's an idiomatic way to print all command line arguments in Rust?
fn main() {
let mut args = std::env::args();
if let Some(arg) = args.next() {
print!("{}", arg);
for arg in args {
print!(" {}", arg);
}
}
}
Or better with Itertools' format or format_with:
use itertools::Itertools; // 0.8.0
fn main() {
println!("{}", std::env::args().format(" "));
}
I just want a space separated String
use itertools::{Itertools, Position};
fn args() -> String {
let mut result = String::new();
let args = std::env::args();
for (position, arg) in args.with_position() {
match position {
Position::First | Position::Only => result.push_str(&arg),
_ => {
result.push(' ');
result.push_str(&arg);
}
}
}
result
}
fn main() {
println!("{}", args());
}
Or similarly, you can use .enumerate() and check if the index is 0 if not using Itertools.
Or
fn args() -> String {
let mut result = String::new();
let mut args = std::env::args();
if let Some(arg) = args.next() {
result.push_str(&arg);
for arg in args {
result.push(' ');
result.push_str(&arg);
}
}
result
}
fn main() {
println!("{}", args());
}
Or
fn args() -> String {
let mut result = std::env::args().fold(String::new(), |s, arg| s + &arg + " ");
result.pop();
result
}
fn main() {
println!("{}", args());
}
If you use Itertools, you can use the format / format_with examples above with the format! macro.
join is also useful:
use itertools::Itertools; // 0.8.0
fn args() -> String {
std::env::args().join(" ")
}
fn main() {
println!("{}", args());
}
In other cases, you may want to use intersperse:
use itertools::Itertools; // 0.8.0
fn args() -> String {
std::env::args().intersperse(" ".to_string()).collect()
}
fn main() {
println!("{}", args());
}
Note this isn't as efficient as other choices as a String is cloned for each iteration.
interspersemethod initertoolsif you're willing to add a dependency. I don't think there's a straightforward way to do this withstd.accumis empty. I'm not sure if this is valid Rust syntax, but I normally do something like:accum + (if accum == "" {""} else {" "}) + &sitertoolsapproach though - there's ajoinfunction initertoolswhich joins all elements into a singleStringseparated by a specified separator..join(" ")or.format_default(" ")