Câu hỏi phỏng vấn Rust
Câu hỏi

What are the differences between String and str in Rust?

Câu trả lời

In Rust, String and str are two distinct types used to handle string data, each with its own characteristics and use cases. Here are the key differences between them:

Ownership and Mutability

  • String:

    • Ownership: String is an owned, heap-allocated data structure. It owns the string data it contains, meaning it is responsible for managing the memory where the string is stored.
    • Mutability: String is mutable, allowing you to modify its contents, such as appending characters or changing existing ones.
    • Usage: Use String when you need to own and modify string data, such as when building strings dynamically or passing strings between threads.
  • str:

    • Ownership: str is a primitive type that represents a sequence of UTF-8 characters. It does not own the data it points to; instead, it is a view or slice into a string.
    • Mutability: str itself is immutable, meaning you cannot change its contents. However, you can have a mutable reference to a str (&mut str), which allows in-place modifications as long as the modifications maintain valid UTF-8.
    • Usage: Use str when you need a read-only view into a string. It is commonly seen as a borrowed reference (&str), which is efficient for passing around string data without transferring ownership.

Memory Allocation

  • String:

    • String is dynamically allocated on the heap, which allows it to grow and shrink in size as needed. This dynamic nature makes it suitable for situations where the string size is not known at compile time.
  • str:

    • str is a dynamically sized type, meaning its size is not known at compile time. It is usually accessed through a reference (&str), which includes a pointer to the data and its length. str can be stored in various places, such as the stack, heap, or even within the binary as a string literal.

Common Operations

  • String:

    • You can create a String using methods like String::new(), String::from(), or by converting from a &str using .to_string().
    • String provides methods for modifying its contents, such as push_str(), push(), and insert().
  • **str*...

junior

junior

Gợi ý câu hỏi phỏng vấn

junior

Explain what is the relationship between Lifetimes and Borrow Checkers in Rust?

middle

How to implement a custom Allocator in Rust?

middle

How would you model a Many-to-Many relationship with a Reference-Counted Smart Pointer in Rust?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào