-
- To allow more generic code.
-
What are the differences between
String
andstr
?String
is the dynamic heap string type, like Vec: use it when you need to own or modify your string data.str
is an immutable sequence of UTF-8 bytes of dynamic length somewhere in memory. Since the size is unknown, one can only handle it behind a pointer. This means that str most commonly2 appears as &str: a reference to some UTF-8 data, normally called a "string slice" or just a "slice".- Use
String
if you need owned string data (like passing strings to other threads, or building them at runtime), and use&str
if you only need a view of a string.
-
Why are explicit lifetimes needed in Rust?
- The main reason is that while the compiler can see what your code does, it doesn't know what your intent was.
-
What is the difference between iter and into_iter?
iter()
iterates over the items by borrowing.into_iter()
iterates over the items, moving them into the new scope (takes ownership).iter_mut()
iterates over the items, giving a mutable reference to each item.