Answers
String
is a fixed-size reference stored in the stack that points to string-type data on the heap.str
is an immutable sequence of bytes stored somewhere in memory. Because the size ofstr
is unknown, it can only be handled by a&
str
pointer.- Since we do not know the size of the string slice at compile time, we cannot allocate the correct amount of memory for it. Strings, on the other hand, have a fixed-size reference stored on the stack that points to the string slice on the heap. Because we know this fixed size of the string reference, we can allocate the correct amount of memory and pass it through to a function.
- We use the HashMap’s
get
function. However, we must remember that theget
function merely returns anOption
struct. If we are confident that there is something there or we want the program to crash if nothing is found, we can directly unwrap it. However, if we don’t want that, we can use amatch
statement and handle theSome
andNone
output as we wish. - No, results must be unwrapped before exposing the error. A simple
match
statement can handle unwrapping the result and managing the error as we see fit. - Rust only allows one mutable borrow to prevent memory unsafety. In Goregaokar’s blog, the example of an enum is used to illustrate this. If an enum supports two different data types (
String
andi64
), if a mutable reference of the string variant of the enum is made, and then another reference is made, the mutable reference can change the data, and then the second reference would still be referencing the string variant of the enum. The second reference would then try to dereference the string variant of the enum, potentially causing a segmentation fault. Elaboration on this example and others is provided in the Further reading section. - We would need to define two different lifetimes when the result of a function relies on one of the lifetimes and the result of the function is needed outside of the scope of where it is called.
- If a struct is referencing itself in one of its fields, the size could be infinite as it could continue to reference itself continuously. To prevent this, we can wrap the reference to the struct in the field in a
Box
struct. - We can slot extra functionality and freedom into a struct by using traits. Implementing a trait will give the struct the ability to use functions that belong to the trait. The trait’s implementation also allows the struct to pass typing checks for that trait.
- We allow a container or function to accept different data structures by declaring enums or traits in the type checking or by utilizing generics (see the Further reading section: Mastering Rust or Hands-On Functional Programming in Rust (first chapter)).
- The quickest way to add a trait to a struct is by annotating the struct with a derive macro that has the copy and clone traits.