In Rust, the standard string types are String and string slices &str. String is a growable, mutable, and owned UTF-8 string type, while &str is typically used as a string borrow, which is a slice pointing to a valid UTF-8 sequence and is immutable.
Creating String
To create a new String in Rust, you can use String::new() to create an empty string, or String::from("specified content") to create a string initialized with content.
rustlet mut s = String::from("Hello");
Updating String
String can be modified in various ways. For example, you can use push_str() to append a string slice or push() to add a single character.
rusts.push_str(", world!"); s.push('!');
Using String and &str
When you want to obtain an immutable reference to a String, you can use the & operator. This creates a &str reference from the String.
rustlet s_slice: &str = &s;
Example: Function Handling Strings
Here is a simple example function that demonstrates how to receive a string slice as a parameter and return a String:
rustfn greet(name: &str) -> String { format!("Hello, {}!", name) } let greeting = greet("Alice"); println!("{}", greeting); // Output: Hello, Alice!
Strings and Error Handling
When handling strings, especially when dealing with external data, errors may occur. For example, attempting to create a string from invalid byte sequences will result in runtime errors. In such cases, it is better to use String::from_utf8 for handling potential errors.
rustlet bytes = vec![0x48, 0x65, 0x6C, 0x6C, 0x6F]; // "Hello" UTF-8 bytes let s = String::from_utf8(bytes); match s { Ok(valid_string) => println!("Converted string: {}", valid_string), Err(e) => println!("Failed to convert: {}", e), }
Through these examples, you can see the basic methods and common use cases for handling String and &str in Rust.