Building strings in Rust
Growing a String, joining pieces, and the cheap ways to slice text.
fn main() {
let mut report = String::new();
report.push_str("tours: ");
report.push_str(&11.to_string());
report.push('\n');
let parts = vec!["basics", "errors", "traits"];
println!("{}", parts.join(" > "));
println!("{}", "-".repeat(20));
let line = " lang = rust ";
if let Some((key, value)) = line.trim().split_once(" = ") {
println!("{key}:{value}");
}
print!("{report}");
}
How it works
push_strappends without allocating a new String.joinputs a separator between the parts.trim,split_onceandstarts_withborrow rather than copy.
Keywords and builtins used here
SomeStringfnifletmainmut
The run, in numbers
- Lines
- 16
- Characters to type
- 382
- Tokens
- 139
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 93 seconds.
Step 3 of 3 in Text, step 29 of 39 in Language basics.