Mastering Rust’s String: Creation, Modification, and Conversion
This article explains Rust’s owned `String` type, showing how to create strings, grow and modify them with various methods, and convert between `String` and `str` while highlighting ownership and borrowing concepts essential for safe memory management.
Rust, a system programming language focused on safety, concurrency, and memory management, provides two main string types: String and string slice str . This article focuses on the owned, mutable, UTF‑8 String type.
String Creation
You can create a String from a literal using either the static method String::from or the to_string method on a string literal.
<code>// Using String::from static method
let hello = String::from("Hello, world!");
// Using to_string method on a literal
let hello = "Hello, world!".to_string();
</code>Both approaches produce a String instance. Unlike C‑style languages, Rust does not append a null terminator to String values.
String Growth and Modification
After creating a String , you can modify and extend it in several ways.
<code>// Create an empty String
let mut s = String::new();
// Append a string slice
s.push_str("Hello");
// Append a single character
s.push(',');
// Concatenate using the + operator or format! macro
let world = " world!";
s = s + world; // using +
// or
s = format!("{}{}", s, world);
println!("{}", s); // prints "Hello, world!"
</code>The + operator consumes the left‑hand String because it calls the add method, which moves the left operand and borrows the right operand as &str .
<code>fn add(self, s: &str) -> String
</code>This means the original String is moved and can no longer be used, while the right‑hand &str is only borrowed.
Conversion Between String and str
Although String and str share many similarities, they differ in ownership: String owns its data, whereas str is typically an immutable borrow. Conversions are common in practice.
<code>// String to &str
let s = String::from("Hello, world!");
let slice = &s[..]; // slice is an &str referencing s
// &str to String
let str_slice = "Hello, world!";
let owned_string = str_slice.to_owned(); // or str_slice.to_string()
</code>Understanding ownership and borrowing is crucial when performing these conversions.
Summary
The article covered how to create a String , modify and grow it, and convert between String and str . While Rust’s String resembles string types in other languages, its unique ownership and borrowing model offers a distinct approach to memory‑safe string handling.
Architecture Development Notes
Focused on architecture design, technology trend analysis, and practical development experience sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.