Rust String
In Rust, a String
is a growable collection of characters stored in heap-allocated memory. Strings are similar to vectors, but they contain Unicode characters instead of bytes, and they have additional methods for manipulating and working with strings.
Here's an example of how to create and use a String
in Rust:
fn main() { let mut s = String::from("hello"); // create a new String with the value "hello" s.push_str(", world!"); // append ", world!" to the String println!("{}", s); // prints "hello, world!" println!("Length: {}", s.len()); // prints "Length: 13" println!("Capacity: {}", s.capacity()); // prints "Capacity: 22" }
In this example, we're creating a new String
called s
with the value "hello" using the String::from
constructor. We're then appending ", world!" to the end of the string using the push_str
method. We're printing the value of the string using the println!
macro, as well as its length and capacity using the len
and capacity
methods.
One important thing to note about String
s in Rust is that they are UTF-8 encoded by default, which means they can contain any Unicode character. Rust's string handling functions are designed to handle Unicode characters and avoid common issues with non-ASCII characters, such as buffer overflows or invalid encoding.
Here's an example of how to iterate over the characters in a String
:
fn main() { let s = String::from("hello"); for c in s.chars() { println!("{}", c); // prints each character of the string on a separate line } }
In this example, we're creating a new String
called s
with the value "hello". We're then iterating over the characters in the string using the chars
method and printing each character on a separate line using the println!
macro.
You can also convert a String
to a &str
(a string slice) using the as_str
method:
fn main() { let s = String::from("hello"); let slice = s.as_str(); println!("{}", slice); // prints "hello" }
In this example, we're creating a new String
called s
with the value "hello". We're then converting the String
to a string slice using the as_str
method and storing it in a variable called slice
. Finally, we're printing the value of the string slice using the println!
macro.