I'm just starting out in Rust and I find the concept of ownership confusing so I wrote an implementation of the echo
command. I would like to know if I could have set the initial value on the echo
variable any better or just any general improvements.
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut echo: String;
if let Some(string) = args.get(1) {
echo = string.to_string();
} else {
return;
}
for arg in &args[2..] {
echo.push(' ');
echo.push_str(arg.as_str());
}
echo.push('\n');
println!("{}", echo);
}
-
2\$\begingroup\$ Actually this answer cover almost all I could say. \$\endgroup\$Stargateur– Stargateur2018年09月12日 17:46:21 +00:00Commented Sep 12, 2018 at 17:46
-
\$\begingroup\$ @Stargateur Thanks a lot! I forgot to mention I didn't want to use any external crates so that works really well for me. \$\endgroup\$Genuinebyte– Genuinebyte2018年09月12日 17:55:05 +00:00Commented Sep 12, 2018 at 17:55
2 Answers 2
I would not say I am any more proficient but I would make these changes if I wrote it.
skip(1)
first arg.join(" ")
instead of iterate though args.
You do not need a mutable value.
use std::env;
fn main() {
let args: Vec<String> = env::args().skip(1).collect();
if args.len() == 0 {
println!("");
} else {
println!("{}", args.join(" "));
}
}
I would do one more thing and send to stdout
since your mimicking echo, but maybe much for this answer.
-
\$\begingroup\$ I didn't realize
env::Args
implemented the Iterator trait. It's definitely more elegant than my code, thanks! \$\endgroup\$Genuinebyte– Genuinebyte2018年09月13日 03:22:22 +00:00Commented Sep 13, 2018 at 3:22 -
\$\begingroup\$ Thank you. Honestly there are more cool tricks, I think you can get away with just join no 'if'. \$\endgroup\$Brandon Clark– Brandon Clark2018年09月13日 07:45:18 +00:00Commented Sep 13, 2018 at 7:45
-
\$\begingroup\$ @Genuinebyte I didn't realize
env::Args
implemented theIterator
trait. — where did you thinkcollect
was coming from? \$\endgroup\$Shepmaster– Shepmaster2018年09月14日 00:27:13 +00:00Commented Sep 14, 2018 at 0:27 -
\$\begingroup\$ What if you just omitted the
if args.len() == 0
branch completely? That would make the code even shorter. \$\endgroup\$Roland Illig– Roland Illig2019年10月16日 01:00:09 +00:00Commented Oct 16, 2019 at 1:00
Use
Iterator::skip
instead of collecting the arguments into aVec
and then skipping over it.This implementation should not have any allocation, whatsoever. Neither collecting the arguments or building an output string is needed.
use std::env;
fn main() {
let mut args = env::args().skip(1);
if let Some(arg) = args.next() {
print!("{}", arg);
for arg in args {
print!(" {}", arg);
}
}
println!();
}