First time using Rust, what do you think about my first try?


#1

This is my first try using Rust. I just tried to pretty-print a vector. Overall experience wasn’t that bad, I actually dig the fact that I can expand the library types with custom methods. My only concern is if someday my custom methods collide with the library methods.

Well, here’s my code, what do you guys think about it?

trait Methods {
	fn append(&mut self, &[&str]) -> &Self;
	fn replace_last(&mut self, &str) -> &Self;
}

impl Methods for String {
	fn append(&mut self, input: &[&str]) -> &Self {
		for e in input {
			self.push_str(e);
		}
		self
	}

	fn replace_last(&mut self, input: &str) -> &Self {
		self.pop();
		self.push_str(input);
		self
	}
}

fn to_string(input: &[&str]) -> String {
	let mut output = String::from("(");
	for e in input {
		output.append(&[e, " "]);
	}
	output.replace_last(")");
	output
}

fn main() {
	let x = vec!["A", "B", "C"];
	println!("{}", to_string(&x));
}

#2

This looks pretty good to me. Three things:

Rust users generally use four spaces, not a tab.

I’m not sure why you use a trait to monkeypatch a String here; these could just as easily be free functions or even inline in to_string.

Also, usually I’d expect a to_string function to be part of https://doc.rust-lang.org/stable/std/string/trait.ToString.html rather than its own free function. Maybe give it a more descriptive name?

These things are relatively minor, though!