Categories
Tags
algorithms APIT Arc arm assembly asynchronous base64 BitHacks Blogging box c clang-format client cmake compiler concat concurrency const_fn contravariant cos covariant cpp Customization cybersecurity DataStructure db debugging Demo deserialization discrete doc DP dtruss Dynamic Example FFI flat_map format FP fsanitize Functional functions futures Fuwari GATs gccrs generics gitignore glibc GUI hacking hashmap haskell heap interop invariant iterator join justfile kernel LaTeX leak LFU linux lto MachineLearning macOS Markdown math ML mmap nc OnceLock optimization OS panic parallels perf physics pin postgresql radare2 release reverse RPIT rust sanitizer science Science serialization server shift sin SmallProjects socket std strace String StringView strip strlen surrealdb SWAR swisstable synchronous tan toml traits triangulation UnsafeRust utf16 utf8 Video wsl x86_64 xilem zig
192 words
1 minutes
250103_string_format_push_str_concat_join_push
link
✅ Summary
| Method | Moves? | Mutable? | Recommended |
|---|---|---|---|
+ | yes | no | sometimes |
format! | no | no | ⭐ best |
push_str | no | yes | ⭐ best for struct |
push | no | yes | char only |
concat() | no | no | slice |
join() | no | no | slice with separator |
There are several ways to concatenate strings
In Rust, there are several ways to concatenate strings, and each one works a little differently because of ownership rules.
Here are the main ways with clear examples.
1. Using + operator (moves left side)
fn main() {
let a = String::from("young");
let b = String::from("ha");
let c = a + &b;
println!("{c}");
}- Output
younghaIMPORTANT
ais moved
let c = a + &b;- is actually:
String::add(a, &b)- So after this,
acannot be used.
2. Using format! (safe, no move)
- Best general method.
fn main() {
let a = String::from("young");
let b = String::from("ha");
let c = format!("{}{}", a, b);
println!("{c}");
println!("{a}");
println!("{b}");
}- Output
youngha
young
ha- ✔ does not move
- ✔ easiest
- ✔ recommended
3. Using push_str (modify existing string)
- Best when mutating struct / variable.
fn main() {
let mut a = String::from("young");
a.push_str("ha");
println!("{a}");
}- Output
youngha4. Using push (single char)
fn main() {
let mut a = String::from("young");
a.push('!');
println!("{a}");
}- Output
young!5. Using concat() (slice of strings)
fn main() {
let a = "young";
let b = "ha";
let c = "kim";
let s = [a, b, c].concat();
println!("{s}");
}- Output
younghakim6. Using join()
fn main() {
let parts = ["young", "ha", "kim"];
let s = parts.join("-");
println!("{s}");
}- Output
young-ha-kim250103_string_format_push_str_concat_join_push
https://younghakim7.github.io/blog/posts/250103_string_format_push_str_concat_join_push/