乐闻世界logo
搜索文章和话题

What are the differences between Rust's ` String ` and ` str `?

1个答案

1

String and str are two primary data types for handling strings in Rust, with key differences and specific use cases:

1. Data Storage:

  • String is a growable, heap-allocated, UTF-8 encoded string type that is mutable, allowing content to be added or modified.
  • str is typically used as &str, a string slice that references a String or other string data in memory. The str type itself is stored in static memory and is immutable.

2. Ownership and Borrowing:

  • String owns its data, and when it goes out of scope, the data is automatically cleaned up.
  • &str does not own the data; it borrows from the actual owner (such as a String or another &str).

3. Performance Considerations:

  • Modifying a String may involve memory reallocation, especially when added data exceeds current capacity.
  • Using &str avoids such performance issues as it is merely a reference to existing data.

4. Use Cases:

  • Use String when you need a mutable string, such as when reading text from a file and modifying or dynamically adding content.
  • Use &str for efficient handling and passing of string data without modification, common in function parameters to avoid data copying and improve efficiency.

Example:

rust
fn main() { let mut s = String::from("hello"); // Create a `String` s.push_str(", world"); // Modify the `String` print_with_prefix(&s); // Pass a reference to the `String` let fixed_str = "fixed string"; // Fixed string, type is `&'static str` print_with_prefix(fixed_str); // Directly pass a string slice } fn print_with_prefix(text: &str) { // Use `&str` as a parameter to enhance function generality and efficiency println!("prefix: {}", text); }

In this example, s is a String that we modify and extend. The print_with_prefix function accepts a &str parameter, demonstrating how &str enhances code flexibility and efficiency.

2024年8月7日 16:53 回复

你的答案