diff --git a/nostarch/chapter04.md b/nostarch/chapter04.md index bed0f376e..48ff8b012 100644 --- a/nostarch/chapter04.md +++ b/nostarch/chapter04.md @@ -3,16 +3,16 @@ # Understanding Ownership -Ownership is important to understand: it's Rust's most unique feature, and -enables Rust to make memory safety guarantees without needing a garbage -collector. We’ll also talk about several related features: borrowing, slices, -and how Rust lays things out in memory. +Ownership is Rust's most unique feature, and enables Rust to make memory safety +guarantees without needing a garbage collector. It's therefore important to +understand how ownership works in Rust. In this chapter we'll talk about +ownership as well as several related features: borrowing, slices, and how Rust +lays things out in memory. ## Ownership -Rust’s central feature is called *ownership*. It is a feature that is -straightforward to explain, but has deep implications for the rest of the -language. +Rust’s central feature is *ownership*. It is a feature that is straightforward +to explain, but has deep implications for the rest of the language. All programs have to manage the way they use a computer's memory while running. Some languages have garbage collection, while in others, the programmer has to @@ -21,7 +21,7 @@ managed through a system of ownership with a set of rules that the compiler checks at compile-time. You do not pay any run-time cost for any of these features. -However, because ownership is a new concept for many programmers, it does take +Since ownership is a new concept for many programmers, it does take some time to get used to. There is good news, though: the more experienced you become with Rust and the rules of the ownership system, the more you'll be able to naturally develop code that is both safe and efficient. Keep at it! @@ -30,23 +30,92 @@ Once you understand ownership, you have a good foundation for understanding the features that make Rust unique. In this chapter, we'll learn ownership by going through some examples, focusing on a very common data structure: strings. -### Variable binding scope +PROD: START BOX + +###### The Stack and the Heap + +In many programming languages, we don't have to think about the stack and the +heap very often. But in a systems programming language like Rust, whether a +value is on the stack or the heap has more of an effect on how the language +behaves and why we have to make certain decisions. We're going to be describing +parts of ownership in relation to the stack and the heap, so here is a brief +explanation. + +Both the stack and the heap are parts of memory that is available to your code +to use at runtime, but they are structured in different ways. The stack stores +values in the order it gets them and removes the values in the opposite order. +This is referred to as *last in, first out*. Think of a stack of plates: when +you add more plates, you put them on top of the pile, and when you need a +plate, you take one off the top. Adding or removing plates from the middle or +bottom wouldn't work as well! Adding data is called *pushing onto the stack* +and removing data is called *popping off the stack*. + +The stack is fast because of the way it accesses the data: it never has to look +around for a place to put new data or a place to get data from; that place is +always the top. Another property that makes the stack fast is that all data on +the stack must take up a known, fixed size. + +For data with a size unknown to us at compile time, or a size that might +change, we can store data on the heap instead. The heap is less organized: when +we put data on the heap, we ask for some amount of space. The operating system +finds an empty spot somewhere in the heap that is big enough, marks it as being +in use, and returns to us a pointer to that location. This process is called +*allocating on the heap*, and sometimes we just say "allocating" for short. +Pushing values onto the stack is not considered allocating. Since the pointer +is a known, fixed size, we can store the pointer on the stack, but when we want +the actual data, we have to follow the pointer. + +Think of being seated at a restaurant. When you enter, you say how many people +are in your group, and the staff finds an empty table that would fit everyone +and leads you there. If someone in your group comes late, they can ask where +you have been seated to find you. + +Accessing data in the heap is slower because we have to follow a pointer to +get there. Allocating a large amount of space can also take time. + +When our code calls a function, the values passed into the function (including, +potentially, pointers to data on the heap) and the function's local variables +get pushed onto the stack. When the function is over, those values get popped +off the stack. + +Keeping track of what parts of code are using what data on the heap, minimizing +the amount of duplicate data on the heap, and cleaning up unused data on the +heap so that we don't run out of space are all problems that ownership +addresses. Once you understand ownership, you won't need to think about the +stack and the heap very often, but knowing that managing heap data is why +ownership exists can help explain why it works the way it does. + +PROD: END BOX + +### Ownership Rules + +First, let's take a look at the rules. Keep these in mind as we go through the +examples that will illustrate the rules: + +> 1. Each value in Rust has a variable binding that’s called its *owner*. +> 2. There can only be one owner at a time. +> 3. When the owner goes out of scope, the value will be dropped. + +### Variable Binding Scope We've walked through an example of a Rust program already in the tutorial chapter. Now that we’re past basic syntax, we won’t include all of the `fn main() {` stuff in examples, so if you’re following along, you will have to put -them inside of a `main()` function. This lets our examples be a bit more -concise, letting us focus on the actual details rather than boilerplate. +the following examples inside of a `main` function yourself. This lets our +examples be a bit more concise, letting us focus on the actual details rather +than boilerplate. -Anyway, here is our first example: +As a first example of ownership, we'll look at the *scope* of some variable +bindings. A scope is the range within a program for which an item is valid. +Let's say we have a variable binding that looks like this: ```rust let s = "hello"; ``` -This variable binding refers to a string literal, where the value of the string -is hard coded into the text of our program. The binding is valid from the point -at which it’s declared until the end of the current _scope_. That is: +The variable binding `s` refers to a string literal, where the value of the +string is hard coded into the text of our program. The binding is valid from +the point at which it’s declared until the end of the current _scope_. That is: ```rust { // s is not valid here, it’s not yet declared @@ -58,31 +127,46 @@ at which it’s declared until the end of the current _scope_. That is: In other words, there are two important points in time here: -- When `s` comes "into scope", it is valid. -- It remains so until it "goes out of scope". +- When `s` comes *into scope*, it is valid. +- It remains so until it *goes out of scope*. At this point, things are similar to other programming languages. Now let’s build on top of this understanding by introducing the `String` type. -### Strings +### The `String` Type -String literals are convenient, but they aren’t the only way that you use -strings. For one thing, they’re immutable. For another, not every string is -literal: what about taking user input and storing it in a string? +In order to illustrate the rules of ownership, we need a data type that is more +complex than the ones we covered in Chapter 3. All of the data types we've +looked at previously are stored on the stack and popped off the stack when +their scope is over, but we want to look at data that is stored on the heap and +explore how Rust knows when to clean that data up. -For this, Rust has a second string type, `String`. You can create a `String` -from a string literal using the `from` function: +We're going to use `String` as the example here and concentrate on the parts of +`String` that relate to ownership. These aspects also apply to other complex +data types provided by the standard library and that you create. We'll go into +more depth about `String` specifically in Chapter XX. + +We've already seen string literals, where a string value is hard-coded into our +program. String literals are convenient, but they aren’t always suitable for +every situation you want to use text. For one thing, they’re immutable. For +another, not every string value can be known when we write our code: what if we +want to take user input and store it? + +For things like this, Rust has a second string type, `String`. This type is +allocated on the heap, and as such, is able to store an amount of text that is +unknown to us at compile time. You can create a `String` from a string literal +using the `from` function, like so: ```rust let s = String::from("hello"); ``` -We haven’t seen the double colon (`::`) syntax yet. It is an operator that -allows us to namespace this particular `from()` function under the `String` -type itself, rather than using some sort of name like `string_from()`. We’ll -discuss this syntax more in the “Method Syntax” and “Modules” chapters. +The double colon (`::`) is an operator that allows us to namespace this +particular `from` function under the `String` type itself, rather than using +some sort of name like `string_from`. We’ll discuss this syntax more in the +“Method Syntax” and “Modules” chapters. -This kind of string can be mutated: +This kind of string *can* be mutated: ```rust let mut s = String::from("hello"); @@ -91,43 +175,43 @@ s.push_str(", world!"); // push_str() appends a literal to a String println!("{}", s); // This will print `hello, world!` ``` - -### Memory and allocation - So, what’s the difference here? Why can `String` be mutated, but literals cannot? The difference comes down to how these two types deal with memory. -In the case of a string literal, because we know the contents of the string at -compile time, we can hard-code the text of the string directly into the final -executable. This means that string literals are quite fast and efficient. But -these properties only come from its immutability. Unfortunately, we can’t put a -blob of memory into the binary for each string whose size is unknown at compile -time and whose size might change over the course of running the program. +### Memory and Allocation -With `String`, in order to support a mutable, growable string, we need to -allocate an unknown amount of memory to hold the contents. This means two -things: +In the case of a string literal, because we know the contents at compile time, +the text is hard-coded directly into the final executable. This makes string +literals quite fast and efficient. But these properties only come from its +immutability. Unfortunately, we can’t put a blob of memory into the binary for +each piece of text whose size is unknown at compile time and whose size might +change over the course of running the program. + +With the `String` type, in order to support a mutable, growable piece of text, +we need to allocate an amount of memory on the heap, unknown at compile time, +to hold the contents. This means two things: 1. The memory must be requested from the operating system at runtime. 2. We need a way of giving this memory back to the operating system when we’re done with our `String`. -That first part is done by us: when we call `String::from()`, its +That first part is done by us: when we call `String::from`, its implementation requests the memory it needs. This is pretty much universal in programming languages. The second case, however, is different. In languages with a *garbage collector* -(*GC*), the GC will keep track and clean up memory that isn't being used -anymore, and we, as the programmer, don’t need to think about it. Without GC, -it’s our responsibility to identify when memory is no longer being used and +(GC), the GC will keep track and clean up memory that isn't being used anymore, +and we, as the programmer, don’t need to think about it. Without GC, it’s the +programmer's responsibility to identify when memory is no longer being used and call code to explicitly return it, just as we did to request it. Doing this -correctly has historically been a difficult problem. If we forget, we will -waste memory. If we do it too early, we will have an invalid variable. If we do -it twice, that’s a bug too. We need to pair exactly one `allocate()` with -exactly one `free()`. +correctly has historically been a difficult problem in programming. If we +forget, we will waste memory. If we do it too early, we will have an invalid +variable. If we do it twice, that’s a bug too. We need to pair exactly one +`allocate` with exactly one `free`. -Rust takes a different path. Remember our example? Here’s a version with -`String`: +Rust takes a different path: the memory is automatically returned once the +binding to it goes out of scope. Here’s a version of our scope example from +earlier using `String`: ```rust { @@ -137,91 +221,99 @@ Rust takes a different path. Remember our example? Here’s a version with } // this scope is now over, and s is no longer valid ``` -We have a natural point at which we can return the memory our `String` needs -back to the operating system: when it goes out of scope. When a variable goes -out of scope, Rust calls a special function for us. This function is called -`drop()`, and it is where the author of `String` can put the code to return the -memory. +There is a natural point at which we can return the memory our `String` needs +back to the operating system: when `s` goes out of scope. When a variable +binding goes out of scope, Rust calls a special function for us. This function +is called `drop`, and it is where the author of `String` can put the code to +return the memory. Rust calls `drop` automatically at the closing `}`. -> Aside: This pattern is sometimes called “Resource Acquisition Is -> Initialization” in C++, or “RAII” for short. While they are very similar, -> Rust’s take on this concept has a number of differences, and so we don’t tend +> Note: This pattern is sometimes called *Resource Acquisition Is +> Initialization* in C++, or RAII for short. While they are very similar, +> Rust’s take on this concept has a number of differences, so we don’t tend > to use the same term. If you’re familiar with this idea, keep in mind that it > is _roughly_ similar in Rust, but not identical. This pattern has a profound impact on the way that Rust code is written. It may -seem obvious right now, but things can get tricky in more advanced situations. -Let’s go over the first one of those right now. +seem simple right now, but things can get tricky in more advanced situations +when we want to have multiple variable bindings use the data that we have +allocated on the heap. Let’s go over some of those situations now. -### Move +#### Ways Bindings and Data Interact: Move -What would you expect this code to do? +There are different ways that multiple bindings can interact with the same data +in Rust. Let's take an example using an integer: ```rust let x = 5; let y = x; ``` -You might say “Make a copy of `5`”, and that would be correct. We now have two -bindings, `x` and `y`, and both equal `5`. +We can probably guess what this is doing based on our experience with other +languages: “Bind the value `5` to `x`, then make a copy of the value in `x` and +bind it to `y`.” We now have two bindings, `x` and `y`, and both equal `5`. +This is indeed what is happening since integers are simple values with a known, +fixed size, and these two `5` values are pushed onto the stack. -Now let’s look at `String`. What would you expect this code to do? +Now let’s look at the `String` version: ```rust let s1 = String::from("hello"); let s2 = s1; ``` -You might say “copy the `String`!” This is both correct and incorrect at the -same time. It does a _shallow_ copy of the `String`. What’s that mean? Well, -let’s take a look at what `String` looks like under the covers: +This looks very similar to the previous code, so we might assume that the way +it works would be the same: that the second line would make a copy of the value +in `s1` and bind it to `s2`. This isn't quite what happens. -string +To explain this more thoroughly, let’s take a look at what `String` looks like +under the covers in Figure 4-1. A `String` is made up of three parts, shown on +the left: a pointer to the memory that holds the contents of the string, a +length, and a capacity. This group of data is stored on the stack. On the right +is the memory that holds the contents, and this is on the heap. -A `String` is made up of three parts: a pointer to the memory that holds the -contents of the string, a length, and a capacity. The length is how much memory -the `String` is currently using. The capacity is the total amount of memory the +String in memory + +Figure 4-1: Representation in memory of a `String` holding the value "hello" +bound to `s1` + +The length is how much memory, in bytes, the contents of the `String` is +currently using. The capacity is the total amount of memory, in bytes, that the `String` has gotten from the operating system. The difference between length -and capacity matters but not in this context, so don’t worry about it too much. -For right now, it's fine to ignore the capacity. +and capacity matters but not in this context, so for now, it's fine to ignore +the capacity. -When we assign `s1` to `s2`, the `String` itself is copied, meaning we copy the -pointer, the length, and the capacity. We do not copy the data that the -`String`'s pointer refers to. In other words, it looks like this: +When we assign `s1` to `s2`, the `String` data itself is copied, meaning we +copy the pointer, the length, and the capacity that are on the stack. We do not +copy the data on the heap that the `String`'s pointer refers to. In other +words, it looks like figure 4-2. -s1 and s2 +s1 and s2 pointing to the same value -_Not_ this: +Figure 4-2: Representation in memory of the binding `s2` that has a copy of +`s1`'s pointer, length and capacity -s1 and s2 to two places +And _not_ Figure 4-3, which is what memory would look like if Rust instead +copied the heap data as well. If Rust did this, the operation `s2 = s1` could +potentially be very expensive if the data on the heap was large. -There’s a problem here. Both data pointers are pointing to the same place. Why -is this a problem? Well, when `s2` goes out of scope, it will free the memory -that the pointer points to. And then `s1` goes out of scope, and it will _also_ -try to free the memory that the pointer points to. That’s bad, and is known as -a "double free" error. +s1 and s2 to two places -So what’s the solution? Here, we stand at a crossroads with a few options. +Figure 4-3: Another possibility for what `s2 = s1` might do, if Rust chose to +copy heap data as well. -One way would be to change assignment so that it will also copy out any data. -This works, but is inefficient: what if our `String` contained a novel? -Also, that solution would only work for memory. What if, instead of a `String`, -we had a `TcpConnection`? Opening and closing a network connection is very -similar to allocating and freeing memory, so it would be nice to be able to use -the same mechanism. We wouldn't be able to, though, because creating a new -connection requires more than just copying memory: we have to request a new -connection from the operating system. We could then extend our solution to -allow the programmer to hook into the assignment, similar to `drop()`, and -write code to fix things up. That would work, but if we did that, an `=` could -run arbitrary code. That’s also not good, and it doesn’t solve our efficiency -concerns either. +Earlier, we said that when a binding goes out of scope, Rust will automatically +call the `drop` function and clean up the heap memory for that binding. But +in figure 4-2, we see both data pointers pointing to the same location. This is +a problem: when `s2` and `s1` go out of scope, they will both try to free the +same memory. This is known as a *double free* error and is one of the memory +safety bugs we mentioned before. Freeing memory twice can lead to memory +corruption, which can potentially lead to security vulnerabilities. -Let’s take a step back: the root of the problem is that `s1` and `s2` both -think that they have control of the memory and therefore need to free it. -Instead of trying to copy the allocated memory, we could say that `s1` is no -longer valid and, therefore, doesn’t need to free anything. This is in fact the -choice that Rust makes. Check out what happens when you try to use `s1` after -`s2` is created: +In order to ensure memory safety, there's one more detail to what happens in +this situation in Rust. Instead of trying to copy the allocated memory, Rust +says that `s1` is no longer valid and, therefore, doesn’t need to free anything +when it goes out of scope. Check out what happens when you try to use `s1` +after `s2` is created: ```rust,ignore let s1 = String::from("hello"); @@ -244,85 +336,80 @@ println!("{}", s1); If you have heard the terms "shallow copy" and "deep copy" while working with other languages, the concept of copying the pointer, length, and capacity -without copying the data probably sounded like a shallow copy. Because Rust +without copying the data probably sounds like a shallow copy. But because Rust also invalidates the first binding, instead of calling this a shallow copy, -it's called a _move_. Here we would read this by saying that `s1` was _moved_ -into `s2`. So what actually happens looks like this: +it's known as a _move_. Here we would read this by saying that `s1` was _moved_ +into `s2`. So what actually happens looks like Figure 4-4. -s1 and s2 to the same place +s1 moved to s2 + +Figure 4-4: Representation in memory after `s1` has been invalidated That solves our problem! With only `s2` valid, when it goes out of scope, it alone will free the memory, and we’re done. -### Ownership Rules - -This leads us to the Ownership Rules: - -> 1. Each value in Rust has a variable binding that’s called its *owner*. -> 2. There can only be one owner at a time. -> 3. When the owner goes out of scope, the value will be `drop()`ped. - Furthermore, there’s a design choice that’s implied by this: Rust will never automatically create "deep" copies of your data. Therefore, any _automatic_ copying can be assumed to be inexpensive. -### Clone +#### Ways Bindings and Data Interact: Clone -But what if we _do_ want to deeply copy the `String`’s data and not just the -`String` itself? There’s a common method for that: `clone()`. We will discuss -methods in the section on `structs` in Chapter XX, but they’re a +If we _do_ want to deeply copy the `String`’s data and not just the `String` +itself, there’s a common method for that: `clone`. We will discuss methods in +the section on `structs` in Chapter XX, but they’re a common enough feature in many programming languages that you have probably seen them before. -Here’s an example of the `clone()` method in action: +Here’s an example of the `clone` method in action: ```rust let s1 = String::from("hello"); let s2 = s1.clone(); -println!("{}", s1); +println!("s1 = {}, s2 = {}", s1, s2); ``` -This will work just fine. Remember our diagram from before? In this case, -it _is_ doing this: +This will work just fine, and this is how you can explicitly get the behavior +we showed in Figure 4-3, where the heap data *does* get copied. -s1 and s2 to two places - -When you see a call to `clone()`, you know that some arbitrary code is being +When you see a call to `clone`, you know that some arbitrary code is being executed, and that code may be expensive. It’s a visual indicator that something different is going on here. -### Copy +#### Stack-only Data: Copy -There’s one last wrinkle that we haven’t talked about yet. This code works: +There’s another wrinkle we haven’t talked about yet. This code, that we showed +earlier, works and is valid: ```rust let x = 5; let y = x; -println!("{}", x); +println!("x = {}, y = {}", x, y); ``` -But why? We don’t have a call to `clone()`. Why didn’t `x` get moved into `y`? +This seems to contradict what we just learned: we don't have a call to +`clone`, but `x` is still valid, and wasn't moved into `y`. -Types like integers that have a known size at compile time do not ask for -memory from the operating system and therefore do not need to be `drop()`ped -when they go out of scope. That means there's no reason we would want to -prevent `x` from being valid after we create the binding `y`. In other words, -there’s no difference between deep and shallow copying here, so calling -`clone()` wouldn’t do anything differently from the usual shallow copying and -we can leave it out. +This is because types like integers that have a known size at compile time are +stored entirely on the stack, so copies of the actual values are quick to make. +That means there's no reason we would want to prevent `x` from being valid +after we create the binding `y`. In other words, there’s no difference between +deep and shallow copying here, so calling `clone` wouldn’t do anything +differently from the usual shallow copying and we can leave it out. -Rust has a special annotation that you can place on types like these, and that -annotation is the `Copy` trait. We'll talk more about traits in Chapter XX. If -a type has the `Copy` trait, an older binding is still usable after assignment. -Rust will not let you make something have the `Copy` trait if it has -implemented `drop()`. If you need to do something special when the value goes -out of scope, being `Copy` will be an error. +Rust has a special annotation called the `Copy` trait that we can place on +types like these (we'll talk more about traits in Chapter XX). If a type has +the `Copy` trait, an older binding is still usable after assignment. Rust will +not let us annotate a type with the `Copy` trait if the type, or any of its +parts, has implemented `drop`. If the type needs something special to happen +when the value goes out of scope and we add the `Copy` annotation to that type, +we will get a compile-time error. So what types are `Copy`? You can check the documentation for the given type to be sure, but as a rule of thumb, any group of simple scalar values can be Copy, -but nothing that requires allocation or is some form of resource is `Copy`. Here’s some of the types that are `Copy`: +and nothing that requires allocation or is some form of resource is `Copy`. +Here’s some of the types that are `Copy`: * All of the integer types, like `u32`. * The booleans, `true` and `false`. @@ -330,56 +417,33 @@ but nothing that requires allocation or is some form of resource is `Copy`. Here * Tuples, but only if they contain types which are also `Copy`. `(i32, i32)` is `Copy`, but `(i32, String)` is not. -### Ownership and functions +### Ownership and Functions -Passing a value to a function has similar semantics as assigning it: +The semantics for passing a value to a function are similar to assigning a +value to a binding. Passing a binding to a function will move or copy, just +like assignment. Here’s an example, with some annotations showing where bindings +go into and out of scope: Filename: src/main.rs ```rust fn main() { - let s = String::from("hello"); + let s = String::from("hello"); // s comes into scope. - takes_ownership(s); - - let x = 5; - - makes_copy(x); -} - -fn takes_ownership(some_string: String) { - println!("{}", some_string); -} - -fn makes_copy(some_integer: i32) { - println!("{}", some_integer); -} -``` - -Passing a binding to a function will move or copy, just like assignment. Here’s -the same example, but with some annotations showing where things go into and -out of scope: - -Filename: src/main.rs - -```rust -fn main() { - let s = String::from("hello"); // s goes into scope. - - takes_ownership(s); // s moves into the function... + takes_ownership(s); // s's value moves into the function... // ... and so is no longer valid here. - let x = 5; // x goes into scope. + let x = 5; // x comes into scope. makes_copy(x); // x would move into the function, // but i32 is Copy, so it’s okay to still // use x afterward. -} // Here, x goes out of scope, then s. But since s was moved, nothing special - // happens. +} // Here, x goes out of scope, then s. But since s's value was moved, nothing + // special happens. fn takes_ownership(some_string: String) { // some_string comes into scope. println!("{}", some_string); -} // Here, some_string goes out of scope and `drop()` is called. The backing +} // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed. fn makes_copy(some_integer: i32) { // some_integer comes into scope. @@ -387,37 +451,14 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope. } // Here, some_integer goes out of scope. Nothing special happens. ``` -Remember: If we tried to use `s` after the call to `takes_ownership()`, Rust +If we tried to use `s` after the call to `takes_ownership`, Rust would throw a compile-time error. These static checks protect us from mistakes. Try adding code to `main` that uses `s` and `x` to see where you can use them and where the ownership rules prevent you from doing so. -Returning values can also transfer ownership: +### Return Values and Scope -Filename: src/main.rs - -```rust -fn main() { - let s1 = gives_ownership(); - - let s2 = String::from("hello"); - - let s3 = takes_and_gives_back(s2); -} - -fn gives_ownership() -> String { - let some_string = String::from("hello"); - - some_string -} - -fn takes_and_gives_back(a_string: String) -> String { - - a_string -} -``` - -With similiar annotations: +Returning values can also transfer ownership. Here's an example with similar annotations: Filename: src/main.rs @@ -452,14 +493,18 @@ fn takes_and_gives_back(a_string: String) -> String { // a_string comes into sco } ``` -It’s the same pattern, every time: assigning something moves it, and when an -owner goes out of scope, if it hasn’t been moved, it will `drop()`. +It’s the same pattern, every time: assigning a value to another binding moves +it, and when heap data values' bindings go out of scope, if the data hasn’t +been moved to be owned by another binding, the value will be cleaned up by +`drop`. -This might seem a bit tedious, and it is. What if we want to let a function use -a value but not take ownership? It’s quite annoying that anything we pass in -also needs to be passed back if we want to use it again, in addition to any -data resulting from the body of the function that we might want to return as -well. It's _possible_ to return multiple values, using a tuple, like this: +Taking ownership then returning ownership with every function is a bit tedious. +What if we want to let a function use a value but not take ownership? It’s +quite annoying that anything we pass in also needs to be passed back if we want +to use it again, in addition to any data resulting from the body of the +function that we might want to return as well. + +It is possible to return multiple values using a tuple, like this: Filename: src/main.rs @@ -480,37 +525,17 @@ fn calculate_length(s: String) -> (String, usize) { ``` But this is too much ceremony and a lot of work for a concept that should be -common. Luckily for us, Rust has a feature for this concept, and it’s what the -next section is about. +common. Luckily for us, Rust has a feature for this concept: references. ## References and Borrowing -At the end of the last section, we had some example Rust that wasn’t very -good. Here it is again: +The issue with the tuple code at the end of the last section is that we have to +return the `String` back to the calling function so that we can still use the +`String` after the call to `calculate_length`, since the `String` was moved +into `calculate_length`. -Filename: src/main.rs - -```rust -fn main() { - let s1 = String::from("hello"); - - let (s2, len) = calculate_length(s1); - - println!("The length of '{}' is {}.", s2, len); -} - -fn calculate_length(s: String) -> (String, usize) { - let length = s.len(); // len() returns the length of a String. - - (s, length) -} -``` - -The issue here is that we have to return the `String` back to the calling -function so that we can still use it there, since it was moved when we called -`calculate_length()`. - -There is a better way. It looks like this: +Here is how you would use a function without taking ownership of it using +*references:* Filename: src/main.rs @@ -532,13 +557,15 @@ fn calculate_length(s: &String) -> usize { First, you’ll notice all of the tuple stuff in the binding declaration and the function return value is gone. Next, note that we pass `&s1` into -`calculate_length()`, and in its definition, we take `&String` rather than +`calculate_length`, and in its definition, we take `&String` rather than `String`. -These `&`s are called *references*, and they allow you to refer to some value -without taking ownership of it. Here’s a diagram: +These `&`s are *references*, and they allow you to refer to some value +without taking ownership of it. Figure 4-5 shows a diagram of this. -DIAGRAM GOES HERE of a &String pointing at a String, with (ptr, len, capacity) +&String s pointing at String s1 + +Figure 4-5: `&String s` pointing at `String s1` Let’s take a closer look at the function call here: @@ -548,9 +575,9 @@ let s1 = String::from("hello"); let len = calculate_length(&s1); ``` -The `&s1` syntax lets us create a reference with `s1`. This reference _refers_ -to the value of `s1` but does not own it. Because it does not own it, the -value it points to will not be dropped when the reference goes out of scope. +The `&s1` syntax lets us create a reference which _refers_ to the value of `s1` +but does not own it. Because it does not own it, the value it points to will +not be dropped when the reference goes out of scope. Likewise, the signature of the function uses `&` to indicate that it takes a reference as an argument. Let’s add some explanatory annotations: @@ -564,17 +591,17 @@ fn calculate_length(s: &String) -> usize { // s is a reference to a String // it refers to, nothing happens. ``` -It’s the same process as before, except that because we don’t have ownership, -we don’t drop what a reference points to when the reference goes out of scope. -This lets us write functions which take references as arguments instead of the -values themselves, so that we won’t need to return them to give back ownership. +It’s the same process as before, but we don’t drop what the reference points to +when it goes out of scope because we don't have ownership. This lets us write +functions which take references as arguments instead of the values themselves, +so that we won’t need to return them to give back ownership. -There’s another word for what references do, and that’s *borrowing*. Just like -with real life, if a person owns something, you can borrow it from them. When -you’re done, you have to give it back. +We call this process *borrowing*. Just like with real life, if a person owns +something, you can borrow it from them, and when you’re done, you have to give +it back. -Speaking of which, what if you try to modify something you borrow from me? Try -this code out. Spoiler alert: it doesn’t work! +So what happens if we try to modify something we're borrowing? Try this code +out. Spoiler alert: it doesn’t work! Filename: src/main.rs @@ -600,12 +627,12 @@ error: cannot borrow immutable borrowed content `*some_string` as mutable | ^^^^^^^^^^^ ``` -Just like bindings are immutable by default, so are references. We’re not -allowed to modify something we have a reference to. +Just as bindings are immutable by default, so are references. We’re not allowed +to modify something we have a reference to. -### Mutable references +### Mutable References -We can fix this bug! Just a small tweak: +We can fix this error with just a small tweak: Filename: src/main.rs @@ -625,7 +652,9 @@ First, we had to change `s` to be `mut`. Then we had to create a mutable reference with `&mut s` and accept a mutable reference with `some_string: &mut String`. -Mutable references have one big restriction, though. This code fails: +Mutable references have one big restriction, though: you can only have one +mutable reference to a particular piece of data in a particular scope. This +code will fail: Filename: src/main.rs @@ -650,10 +679,16 @@ error[E0499]: cannot borrow `s` as mutable more than once at a time | - first borrow ends here ``` -The error is what it says: you cannot borrow something mutably more than once -at a time. This restriction allows for mutation but in a very controlled -fashion. It is something that new Rustaceans struggle with, because most -languages let you mutate whenever you’d like. +This restriction allows for mutation but in a very controlled fashion. It is +something that new Rustaceans struggle with, because most languages let you +mutate whenever you’d like. The benefit of having this restriction is that Rust +can prevent data races at compile time. A *data race* is a particular type of +race condition where two or more pointers access the same data at the same +time, at least one of the pointers is being used to write to the data, and +there's no mechanism being used to synchronize access to the data. Data races +cause undefined behavior and can be difficult to diagnose and fix when trying +to track them down at runtime; Rust prevents this problem from happening since +it won't even compile code with data races! As always, we can use `{}`s to create a new scope, allowing for multiple mutable references, just not _simultaneous_ ones: @@ -697,15 +732,24 @@ error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immuta Whew! We _also_ cannot have a mutable reference while we have an immutable one. Users of an immutable reference don’t expect the values to suddenly change out -from under them! Multiple immutable references are okay, however. +from under them! Multiple immutable references are okay, however, since no one +who is just reading the data has the ability to affect anyone else's reading of +the data. -### Dangling references +Even though these errors may be frustrating at times, remember that it's the +Rust compiler pointing out a potential bug earlier (at compile time rather than +at runtime) and showing you exactly where the problem is instead of you having +to track down why sometimes your data isn't what you thought it should be. -In languages with pointers, it’s easy to create a “dangling pointer” by freeing -some memory while keeping around a pointer to that memory. In Rust, by -contrast, the compiler guarantees that references will never be dangling: if we -have a reference to something, the compiler will ensure that it will not go -out of scope before the reference does. +### Dangling References + +In languages with pointers, it's easy to make the error of creating a *dangling +pointer*, a pointer referencing a location in memory that may have been given +to someone else, by freeing some memory while keeping around a pointer to that +memory. In Rust, by contrast, the compiler guarantees that references will +never be dangling: if we have a reference to some data, the compiler will +ensure that the data will not go out of scope before the reference to the data +does. Let’s try to create a dangling reference: @@ -739,16 +783,14 @@ error[E0106]: missing lifetime specifier error: aborting due to previous error ``` -This error message refers to a feature we haven’t learned about yet, -*lifetimes*. The message does contain the key to why this code is a problem, -though: +This error message refers to a feature we haven’t learned about yet: +*lifetimes*. We'll discuss lifetimes in detail in Chapter XX, but, disregarding +the parts about lifetimes, the message does contain the key to why this code is +a problem: `this function’s return type contains a borrowed value, but there is +no value for it to be borrowed from`. -```bash -this function’s return type contains a borrowed value, but there is no value -for it to be borrowed from -``` - -Let’s examine exactly what happens with `dangle()`: +Let’s have a closer look at exactly what's happenening at each stage of our +`dangle` code: ```rust,ignore fn dangle() -> &String { // dangle returns a reference to a String @@ -760,7 +802,7 @@ fn dangle() -> &String { // dangle returns a reference to a String // Danger! ``` -Because `s` is created inside of `dangle()`, when the code of `dangle()` is +Because `s` is created inside of `dangle`, when the code of `dangle` is finished, it will be deallocated. But we tried to return a reference to it. That means this reference would be pointing to an invalid `String`! That’s no good. Rust won’t let us do this. @@ -790,14 +832,14 @@ Next, let's look at a different kind of reference: slices. ## Slices -So far, we’ve talked about types that have ownership, like `String`, and ones -that don’t, like `&String`. There is another kind of type which does not have -ownership: slices. Slices let you reference a contiguous sequence of elements -in a collection rather than the whole collection itself. +There is another data type which does not have ownership: slices. Slices let +you reference a contiguous sequence of elements in a collection rather than the +whole collection itself. -Here’s a small programming problem: write a function which takes a string -and returns the first word you find. If we don’t find a space in the string, -then the whole string is a word, so the whole thing should be returned. +Here’s a small programming problem: write a function which takes a string and +returns the first word it finds in that string. If it doesn’t find a space in +the string, it means the whole string is one word, so the whole thing should be +returned. Let’s think about the signature of this function: @@ -834,22 +876,22 @@ let bytes = s.as_bytes(); Since we need to go through the String element by element and check if a value is a space, we will convert our String to an -array of bytes using the `.as_bytes()` method. +array of bytes using the `as_bytes` method. ```rust,ignore for (i, &item) in bytes.iter().enumerate() { ``` -We will be discussing iterators in more detail in Chapter XX, but for -now, know that `iter()` is a method that returns each element in a -collection, and `enumerate()` modifies the result of `iter()` and returns -a tuple instead. The first element of the tuple is the index, and the -second element is a reference to the element itself. This is a bit -nicer than calculating the index ourselves. +We will be discussing iterators in more detail in Chapter XX, but for now, know +that `iter` is a method that returns each element in a collection, and +`enumerate` modifies the result of `iter` and returns each element as part +of a tuple instead, where the first element of the tuple is the index, and the +second element is a reference to the element itself. This is a bit nicer than +calculating the index ourselves. Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we -match against the tuple with i for the index and &item for a single byte. Since -we get a reference from `.iter().enumerate()`, we use `&` in the pattern. +match against the tuple with `i` for the index and `&item` for a single byte. +Since we get a reference from `.iter().enumerate()`, we use `&` in the pattern. ```rust,ignore if item == b' ' { @@ -860,13 +902,15 @@ s.len() ``` We search for the byte that represents the space, using the byte literal -syntax. If we find one, we return the position. Otherwise, we return the length -of the string, using `s.len()`. +syntax. If we find a space, we return the position. Otherwise, we return the +length of the string, using `s.len()`. -This works, but there’s a problem. We’re returning a `usize` on its own, but -it’s only a meaningful number in the context of the `&String`. In other -words, because it’s a separate value from the `String`, there’s no guarantee -that it will still be valid in the future. Consider this: +We now have a way to find out the index of the end of the first word in the +string, but there’s a problem. We’re returning a `usize` on its own, but it’s +only a meaningful number in the context of the `&String`. In other words, +because it’s a separate value from the `String`, there’s no guarantee that it +will still be valid in the future. Consider this program that uses this +`first_word` function: Filename: src/main.rs @@ -883,22 +927,29 @@ fn main() { } ``` -This is bad! It’s even worse if we wanted to write a `second_word()` +This program compiles without any errors, and also would if we used `word` +after calling `s.clear()`. `word` isn't connected to the state of `s` at all, +so `word` still contains the value `5`. We could use that `5` with `s` to try +to extract the first word out, but this would be a bug since the contents of +`s` have changed since we saved `5` in `word`. + +This is bad! It’s even worse if we wanted to write a `second_word` function. Its signature would have to look like this: ```rust,ignore fn second_word(s: &String) -> (usize, usize) { ``` -Now we’re tracking both a start _and_ an ending index. Even more chances for -things to go wrong. We now have three unrelated variable bindings floating +Now we’re tracking both a start _and_ an ending index, and we have even more +values that were calculated from data in a particular state but aren't tied to +that state at all. We now have three unrelated variable bindings floating around which need to be kept in sync. Luckily, Rust has a solution to this problem: string slices. -## String slices +### String Slices -A string slice looks like this: +A string slice is a reference to part of a `String`, and looks like this: ```rust let s = String::from("hello world"); @@ -907,19 +958,21 @@ let hello = &s[0..5]; let world = &s[6..11]; ``` -This looks just like taking a reference to the whole `String`, but with the -extra `[0..5]` bit. Instead of being a reference to the entire `String`, it’s a +This is similar to taking a reference to the whole `String`, but with the +extra `[0..5]` bit. Rather than a reference to the entire `String`, it’s a reference to an internal position in the `String` and the number of elements that it refers to. -We can create slices with a range of `[starting_index..ending_index]`, but the +We create slices with a range of `[starting_index..ending_index]`, but the slice data structure actually stores the starting position and the length of the slice. So in the case of `let world = &s[6..11];`, `world` would be a slice that contains a pointer to the 6th byte of `s` and a length value of 5. -In other words, it looks like this: +Figure 4-6 shows this in a diagram: -DIAGRAM GOES HERE of s, hello, and world +world containing a pointer to the 6th byte of String s and a length 5 + +Figure 4-6: Two string slices referring to parts of a `String` With Rust’s `..` range syntax, if you want to start at the first index (zero), you can drop the value before the `..`. In other words, these are equal: @@ -956,7 +1009,8 @@ let slice = &s[0..len]; let slice = &s[..]; ``` -With this in mind, let’s re-write `first_word()` to return a slice: +With this in mind, let’s re-write `first_word` to return a slice. The type +that signifies "string slice" is written as `&str`: Filename: src/main.rs @@ -974,20 +1028,28 @@ fn first_word(s: &String) -> &str { } ``` -Now we have a single value, the `&str`, pronounced "string slice". It stores -both elements that we care about: a reference to the starting point of the -slice and the number of elements in the slice. +We get the index for the end of the word in the same way as before, by looking +for the first occurrence of a space. When we find a space, we return a string +slice using the start of the string and the index of the space as the starting +and ending indices. -This would also work for a `second_word()`: +Now when we call `first_word`, we get back a single value that is tied to the +underlying data. The value is made up of a reference to the starting point of +the slice and the number of elements in the slice. + +Returning a slice would also work for a `second_word` function: ```rust,ignore fn second_word(s: &String) -> &str { ``` -We now have a straightforward API that’s much harder to mess up. - -But what about our error condition from before? Slices also fix that. Using -the slice version of `first_word()` will throw an error: +We now have a straightforward API that’s much harder to mess up. Remember our +bug from before, when we got the first word but then cleared the string so that +our first word was invalid? That code was logically incorrect but didn't show +any immediate errors. The problems would show up later, if we kept trying to +use the first word index with an emptied string. Slices make this bug +impossible, and let us know we have a problem with our code much sooner. Using +the slice version of `first_word` will throw a compile time error: Filename: src/main.rs @@ -1001,7 +1063,7 @@ fn main() { } ``` -Here’s the error: +Here’s the compiler error: ```bash 17:6 error: cannot borrow `s` as mutable because it is also borrowed as @@ -1019,13 +1081,13 @@ fn main() { ^ ``` -Remember the borrowing rules? If we have an immutable reference to something, -we cannot also take a mutable reference. Since `clear()` needs to truncate the -`String`, it tries to take a mutable reference, which fails. Not only has Rust -made our API easier to use, but it’s also eliminated an entire class of errors -at compile time! +Remember from the borrowing rules that if we have an immutable reference to +something, we cannot also take a mutable reference. Since `clear` needs to +truncate the `String`, it tries to take a mutable reference, which fails. Not +only has Rust made our API easier to use, but it’s also eliminated an entire +class of errors at compile time! -### String literals are slices +#### String Literals are Slices Remember how we talked about string literals being stored inside of the binary itself? Now that we know about slices, we can now properly understand string @@ -1039,26 +1101,25 @@ The type of `s` here is `&str`: It’s a slice, pointing to that specific point of the binary. This is also why string literals are immutable; `&str` is an immutable reference. -### String slices as arguments +#### String Slices as Arguments Knowing that you can take slices of both literals and `String`s leads us to -one more improvement on `first_word()`, and that’s its signature: +one more improvement on `first_word`, and that’s its signature: ```rust,ignore fn first_word(s: &String) -> &str { ``` -A more experienced Rustacean would write this one instead: +A more experienced Rustacean would write this one instead because it allows us +to use the same function on both `String`s and `&str`s: ```rust,ignore fn first_word(s: &str) -> &str { ``` -Why is this? Well, we aren’t trying to modify `s` at all. And we can take -a string slice that’s the full length of a `String`, so we haven’t lost -the ability to talk about full `String`s. And additionally, we can take -string slices of string literals too, so this function is more useful, but -with no loss of functionality: +If we have a string slice, we can pass that as the argument directly. If we +have a `String`, we can pass a slice of the entire `String`. This makes our API +more general and useful without losing any functionality: Filename: src/main.rs @@ -1080,17 +1141,17 @@ fn main() { } ``` -## Other slices +### Other Slices String slices, as you might imagine, are specific to strings. But there’s a more -general slice type, too. Consider arrays: +general slice type, too. Consider this array: ```rust let a = [1, 2, 3, 4, 5]; ``` Just like we may want to refer to a part of a string, we may want to refer to -part of an array: +part of an array, and would do so like this: ```rust let a = [1, 2, 3, 4, 5]; @@ -1102,3 +1163,16 @@ This slice has the type `&[i32]`. It works the exact same way as string slices do, by storing a reference to the first element and a length. You’ll use this kind of slice for all sorts of other collections. We’ll discuss these in detail when we talk about vectors in Chapter XX. + +## Summary + +The concepts of ownership, borrowing, and slices are what ensure memory safety +in Rust programs at compile time. Rust is a language that gives you control +over your memory usage like other systems programming languages, but having the +owner of data automatically clean up that data when the owner goes out of scope +means you don't have to write and debug extra code to get this control. + +Ownership affects how lots of other parts of Rust work, so we will be talking +about these concepts further throughout the rest of the book. Let's move on to +the next chapter where we'll look at grouping pieces of data together in a +`struct`. diff --git a/nostarch/chapter07.md b/nostarch/chapter07.md new file mode 100644 index 000000000..7f6afcd6b --- /dev/null +++ b/nostarch/chapter07.md @@ -0,0 +1,872 @@ + +[TOC] + +# Modules + +When you write a program in Rust, your code might start off living solely in +the `main` function. As your code grows, you eventually move functionality out +into functions, both for re-use and for nicer organization. By splitting your +code up into smaller chunks, each chunk is easier to understand on its own. So +what happens when you start having too many functions? Rust has a module system +that tackles both the problem of wanting to be able to re-use code and the +problem of keeping your code organized. + +In the same way that you extract lines of code into a function, you can extract +functions (and other code like structs and enums too) into different modules. A +*module* is a namespace that contains definitions of functions or types, and +those definitions can be visible outside their module or not. Here's an +overview of how the bits fit together: + +* `mod` declares a new module. +* Everything starts off as private, but the `pub` keyword makes it public. +* The `use` keyword allows you to bring modules, or definitions inside of them, + into scope so that it's easier to refer to them. + +We'll take a look at each of these parts and see how they fit into the whole. + +## `mod` and the Filesystem + +Every module in Rust starts with the `mod` keyword. In this next example, we'll +start again by making a new project with Cargo. This time, instead of a binary, +we're going to make a library: a project that other people would pull into their +projects as a dependency. We saw this with the `rand` crate in Chapter 2. + +Imagine that we're creating a library to provide some general networking +functionality, and we decide to call our library `communicator`. To create this +library, we won't use the `--bin` option like we have before. This is because +by default cargo will create a library: + +```bash +$ cargo new communicator +$ cd communicator +``` + +Notice that Cargo generated `src/lib.rs` instead of `src/main.rs` for us, and +inside it we'll find this: + +Filename: src/lib.rs + +```rust +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + } +} +``` + +This is an empty test to help us get our library started, instead of the binary +that says "Hello, world!" that we get with the `--bin` option. Let's ignore the +`#[]` stuff and `mod tests` for a little bit, but we'll make sure to leave it +in `src/lib.rs` for later. + +We're going to look at different ways we could choose to organize our library's +code, any of which could make sense depending on exactly what we were trying to +do. To start, add this code at the beginning of the file: + +Filename: src/lib.rs + +```rust +mod network { + fn connect() { + } +} +``` + +This is our first module declaration. We use the `mod` keyword, followed by the +name of the module, and then a block of code in curly braces. Everything inside +this block is inside the namespace `network`. In this case, we have a single +function, `connect`. If we wanted to try and call this function from outside +the `network` module, we would say `network::connect()` rather than `connect()`. + +We could have multiple modules, side-by-side. For example, if we wanted a +`client` module: + +Filename: src/lib.rs + +```rust +mod network { + fn connect() { + } +} + +mod client { + fn connect() { + } +} +``` + +Now we have a `network::connect` function and a `client::connect` function. + +And we can put modules inside of modules. If we wanted to have `client` be +within `network`: + +Filename: src/lib.rs + +```rust +mod network { + fn connect() { + } + + mod client { + fn connect() { + } + } +} +``` + +This gives us `network::connect` and `network::client::connect`. + +In this way, modules form a tree. The contents of `src/lib.rs` are at the root +of the project's tree, and the submodules form the leaves. Here's what our +first example looks like when thought of this way: + +```text +communicator + ├── network + └── client +``` + +And here's the second: + +```text +communicator + └── network + └── client +``` + +More complicated projects can have a lot of modules. + +### Putting Modules in Another File + +Modules form a hierarchical, tree-like structure. So does another thing: +file systems! The module system is the way that we split larger Rust projects up +into multiple files. Let's imagine we have a module layout like this: + +File: src/lib.rs + +```rust +mod client { + fn connect() { + } +} + +mod network { + fn connect() { + } + + mod server { + fn connect() { + } + } +} +``` + +Let's extract the `client` module into another file. First, we need to change +our code in `src/lib.rs`: + +File: src/lib.rs + +```rust,ignore +mod client; + +mod network { + fn connect() { + } + + mod server { + fn connect() { + } + } +} +``` + +We still say `mod client`, but instead of curly braces, we have a semicolon. +This lets Rust know that we have a module, but it's in another file with that +module's name. Open up `src/client.rs` and put this in it: + +File: src/client.rs + +```rust +fn connect() { +} +``` + +Note that we don't need a `mod` declaration in this file. `mod` is for +declaring a new module, and we've already declared this module in `src/lib.rs`. +This file provides the _contents_ of the `client` module. If we put a `mod +client` here, we'd be giving the `client` module its own submodule named +`client`! + +Now, everything should compile successfully, but with a few warnings: + +```bash +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/client.rs:1:1 + | +1 | fn connect() { + | ^ + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/lib.rs:4:5 + | +4 | fn connect() { + | ^ + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/lib.rs:8:9 + | +8 | fn connect() { + | ^ +``` + +Don't worry about those warnings for now; we'll clear them up in a future +section. They're just warnings, we've built things successfully! + +Let's extract the `network` module into its own file next, using the same +pattern. Change `src/lib.rs` to look like this: + +Filename: src/lib.rs + +```rust,ignore +mod client; + +mod network; +``` + +And then put this in `src/network.rs` + +Filename: src/network.rs + +```rust +fn connect() { +} + +mod server { + fn connect() { + } +} +``` + +And then run `cargo build` again. Success! We have one more module to extract: +`server`. Unfortunately, our current tactic of extracting a module into a file +named after that module won't work. Let's try it anyway. Modify +`src/network.rs` to look like this: + +Filename: src/network.rs + +```rust,ignore +fn connect() { +} + +mod server; +``` + +Put this in `src/server.rs` + +Filename: src/server.rs + +```rust +fn connect() { +} +``` + +When we try to `cargo build`, we'll get an error: + +```bash +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) +error: cannot declare a new module at this location + --> src/network.rs:4:5 + | +4 | mod server; + | ^^^^^^ + | +note: maybe move this module `network` to its own directory via `network/mod.rs` + --> src/network.rs:4:5 + | +4 | mod server; + | ^^^^^^ +note: ... or maybe `use` the module `server` instead of possibly redeclaring it + --> src/network.rs:4:5 + | +4 | mod server; + | ^^^^^^ +``` + +This error is actually pretty helpful. It points out something we didn't know +that we could do yet: + +> note: maybe move this module `network` to its own directory via +`network/mod.rs` + +Here's the problem: in our case, we have different names for our modules: +`client` and `network::server`. But what if we had `client` and +`network::client`, or `server` and `network::server`? Having two modules at +different places in the module hierarchy have the same name is completely +valid, but then which module would the files `src/client.rs` and +`src/server.rs`, respectively, be for? + +Instead of continuing to follow the same file naming pattern we used +previously, we can do what the error suggests. We'll make a new _directory_, +move `src/server.rs` into it, and change `src/network.rs` to +`src/network/mod.rs`. Then, when we try to build: + +```bash +$ mkdir src/network +$ mv src/server.rs src/network +$ mv src/network.rs src/network/mod.rs +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) + +$ +``` + +It works! So now our module layout looks like this: + +```text +communicator + ├── client + └── network + └── server +``` + +And the corresponding file layout looks like this: + +```text +├── src +│   ├── client.rs +│   ├── lib.rs +│   └── network +│   ├── mod.rs +│   └── server.rs +``` + +In summary, these are the rules of modules with regards to files: + +* If a module named `foo` has no submodules, you should put the declarations in + the `foo` module in a file named `foo.rs`. +* If a module named `foo` does have submodules, you should put the declarations + for `foo` in a file named `foo/mod.rs`. +* The first two rules apply recursively, so that if a module named `foo` has a + submodule named `bar` and `bar` does not have submodules, you should have the + following files in your `src` directory: + + ```text + ├── foo + │   ├── bar.rs (contains the declarations in `foo::bar`) + │   └── mod.rs (contains the declarations in `foo`, including `mod bar`) + ``` + +* The modules themselves should be declared in their parent module's file using + the `mod` keyword. + +Next, we'll talk about the `pub` keyword, and get rid of those warnings! + +## Controlling Visibility with `pub` + +At the end of the last section, we had a project, `communicator`, and when we compiled it, we got some strange warnings: + +```bash + Compiling communicator v0.1.0 (file:///projects/communicator) +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/client.rs:1:1 + | +1 | fn connect() { + | ^ + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/mod.rs:1:1 + | +1 | fn connect() { + | ^ + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/server.rs:1:1 + | +1 | fn connect() { + | ^ +``` + +Why does this happen? After all, we're building a library. What if these three +functions are the public interface that we want our *users* to use? We won't +necessarily be using them within our own project, but the point of creating them +is that they *will* be used by another project. Let's try using them as if we +were another project using our library to see what happens and understand why +we're getting these unused function warnings. Create a `src/main.rs` file with +this code: + +Filename: src/main.rs + +```rust,ignore +extern crate communicator; + +fn main() { + communicator::client::connect(); +} +``` + +We need the `extern crate` line to bring our `communicator` library crate into +scope, because our package actually now contains *two* crates. Cargo treats +src/main.rs as the crate root of a binary crate, and we also have our existing +library crate. This pattern is quite common for executable crates: most +functionality is in a library crate, and the executable crate uses that +library. This way, other programs can also use the library crate, and it’s a +nice separation of concerns. + +Our binary crate right now just calls our library's `connect` function from +the `client` module; we picked that one since it's the first warning in our +build output above. Invoking `cargo build` will now give us an error after the +warnings: + +```bash +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) +error: module `client` is private + --> src/main.rs:4:5 + | +4 | communicator::client::connect(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +``` + +Ah ha! The `client` module is private. This is the first time we've run into +the concepts of 'public' and 'private' in the context of Rust. There's no +keyword to make something private; that's the default state. In this default +state, no one else could possibly use it, so if we don't use it within our +library crate, Rust will warn us that it's unused. Once we tell Rust something +is public, Rust knows that we intend for code external to our crate to use it, +and Rust considers theoretical external usage that is now possible to count as +being used. Thus, when something is marked as public, Rust will stop warning us +that it is unused. + +To tell Rust we want to make something public, we add the `pub` keyword. This +keyword goes before the declaration of the item we want to make public. Let's +modify `src/lib.rs` to make the `client` module public to fix the error we got: + +Filename: src/lib.rs + +```rust,ignore +pub mod client; + +mod network; +``` + +The `pub` goes right before `mod`. Let's try building again: + +```bash +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) + +error: function `connect` is private + --> src/main.rs:4:5 + | +4 | communicator::client::connect(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +``` + +Hooray! We have a different error! Yes, different error messages are a cause +for celebration. The new error says "function `connect` is private", so let's +edit `src/client.rs` to make `client::connect` public: + +Filename: src/client.rs + +```rust +pub fn connect() { +} +``` + +And run `cargo build` again: + +```bash + cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/mod.rs:1:1 + | +1 | fn connect() { + | ^ + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/server.rs:1:1 + | +1 | fn connect() { + | ^ +``` + +It compiled! And the warning about `client::connect` not being used is gone! + +Making functions public isn't the only way to fix unused code warnings: if +we *didn't* want these functions to be part of our public API and we got these +warnings, the warnings could be alerting us to code we no longer needed and +could safely delete. They could also be alerting us to a bug, if we +had just accidentally removed all places within our library where we called +this function. + +However, we *do* want the other two functions to be part of our crate's public +API, so let's mark them as `pub` as well to get rid of the remaining warnings. +Modify `src/network/mod.rs` to be: + +Filename: src/network/mod.rs + +```rust,ignore +pub fn connect() { +} + +mod server; +``` + +And compile: + +```bash +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/mod.rs:1:1 + | +1 | pub fn connect() { + | ^ + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/server.rs:1:1 + | +1 | fn connect() { + | ^ +``` + +Hmmm, it says this is still dead, even though it's `pub`. While the function is +public within the module, the `network` module it's in is not public. We're +working from the interior of the library out this time, as opposed to with +`client` where we worked from the outside in. Let's change `src/lib.rs` to add +the same fix though, by making `network` public like `client` is: + +Filename: src/lib.rs + +```rust,ignore +pub mod client; + +pub mod network; +``` + +Now if we compile, that warning is gone: + +```bash +$ cargo build + Compiling communicator v0.1.0 (file:///projects/communicator) +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/server.rs:1:1 + | +1 | fn connect() { + | ^ +``` + +Only one last warning! Try to fix this one on your own! + +### Privacy Rules + +Overall, these are the rules for item visibility: + +1. If an item is public, then it can be accessed through any of its + parent modules. +2. If an item is private, it may be accessed by the current module and its + child modules. + +Let's look at a few more examples to get some practice. What if we had this +code in a new project's `src/lib.rs`: + +Filename: src/lib.rs + +```rust,ignore +mod outermost { + pub fn middle_function() {} + + fn middle_secret_function() {} + + mod inside { + pub fn inner_function() {} + + fn secret_function() {} + } +} + +fn try_me() { + outermost::middle_function(); + outermost::middle_secret_function(); + outermost::inside::inner_function(); + outermost::inside::secret_function(); +} +``` + +Before you try to compile this code, make a guess about which lines in +`try_me` will have errors. + +Ready? Let's talk through them! + +The `try_me` function is in the root module of our project. The module named +`outermost` is private, but the second rule says we're allowed to access it +since `outermost` is in our current, root module. + +The function call `outermost::middle_function()` will work. `middle_function` +is public, and we are accessing it through its parent module, `outermost`, +which we just determined we can access in the previous paragraph. + +`outermost::middle_secret_function()` will cause a compilation error. +`middle_secret_function` is private, so the second rule applies. Our current +root module is neither the current module of `middle_secret_function` +(`outermost` is), nor is it a child module of the current module of +`middle_secret_function`. + +The module named `inside` is private and has no child modules, so it can only +be accessed by its current module, `outermost`. That means the `try_me` +function is not allowed to call `outermost::inside::inner_function()` or +`outermost::inside::secret_function()`. + +Here are some changes to try making with this code. Try each one, make a guess +about what will be allowed or not, compile to see if you're right, and use the +rules to understand why. + +* What if the `inside` module was public? +* What if `outside` was public and `inside` was private? +* What if, in the body of `inner_function`, we called + `::outermost::middle_secret_function()`? (The two colons at the beginning + mean that we want to refer to the namespaces starting from the root + namespace.) + +Feel free to design more experiments and try them out! + +Next, let's talk about bringing items into a scope with the `use` keyword. + +## Importing Names with `use` + +We've seen how we can call functions defined within a module by using the +module name as part of the call, like this: + +Filename: src/main.rs + +```rust +pub mod a { + pub mod series { + pub mod of { + pub fn namespaces() {} + } + } +} + +fn main() { + a::series::of::namespaces(); +} +``` + +However, referring to the fully qualified name can get quite lengthy, as we see +in that example. To solve this issue, Rust has a keyword, `use`. It works like +this: + +Filename: src/main.rs + +```rust +pub mod a { + pub mod series { + pub mod of { + pub fn namespaces() {} + } + } +} + +use a::series::of; + +fn main() { + of::namespaces(); +} +``` + +We can `use` a module, and that will bring its name into scope. This allows us +to shorten our function call, only requiring us to type the final module name, +not the entire chain of them. `use` is quite powerful and can bring all kinds +of things into scope. For example, we could `use` the function itself: + +```rust +pub mod a { + pub mod series { + pub mod of { + pub fn namespaces() {} + } + } +} + +use a::series::of::namespaces; + +fn main() { + namespaces(); +} +``` + +Enums also form this kind of namespace; we can import an enum's variants with +`use` as well. For any kind of `use` statement, if you are importing multiple +items from one namespace, you can list them using curly braces and commas in +the last position, like so: + +```rust +enum TrafficLight { + Red, + Yellow, + Green, +} + +use TrafficLight::{Red, Yellow}; + +fn main() { + let red = Red; + let yellow = Yellow; + let green = TrafficLight::Green; // because we didn't use TrafficLight::Green +} +``` + +### Glob Imports with `*` + +If you'd like to import all the items in a namespace at once, you can use `*`: + +```rust +enum TrafficLight { + Red, + Yellow, + Green, +} + +use TrafficLight::*; + +fn main() { + let red = Red; + let yellow = Yellow; + let green = Green; +} +``` + +The `*` is called a 'glob', and it will import everything that's visible inside +of the namespace. Globs should be used sparingly: they are convenient, but you +might also pull in more things than you expected and cause naming conflicts. + +### Using `super` to Access a Parent Module + +Remember when we created our crate that Cargo made a `tests` module for us? +Let's talk about that now. It was in `src/lib.rs`: + +Filename: src/lib.rs + +```rust,ignore +pub mod client; + +pub mod network; + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + } +} +``` + +We'll explain more about testing in Chapter XX, but parts of this should make +sense now: we have a module named `tests` that lives next to our other modules +and contains one function named `it_works`. Even though there are special +annotations, the `tests` module is just another module! + +Since tests are for exercising the code within our library, let's try to call +our `client::connect` function from this `it_works` function, even though +we're not going to be checking any functionality right now: + +Filename: src/lib.rs + +```rust +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + client::connect(); + } +} +``` + +Run the tests by invoking the `cargo test` command: + +```bash +$ cargo test + Compiling communicator v0.1.0 (file:///projects/communicator) +error[E0433]: failed to resolve. Use of undeclared type or module `client` + --> src/lib.rs:9:9 + | +9 | client::connect(); + | ^^^^^^^^^^^^^^^ Use of undeclared type or module `client` + +warning: function is never used: `connect`, #[warn(dead_code)] on by default + --> src/network/server.rs:1:1 + | +1 | fn connect() { + | ^ +``` + +Why doesn't this compile? It's not because we don't have `communicator::` in +front of the function like we had in `src/main.rs`: we are definitely within +the `communicator` library crate here. The reason is that paths anywhere except +in a `use` statement are relative to the current module (In a `use` statement, +they're relative to the crate root by default). Our `tests` module doesn't have +a `client` module in its scope! + +So how do we get back up one module? We can either use leading colons to say +that we want to start from the root and list the whole path: + +```rust,ignore +::client::connect(); +``` + +Or we can use `super` to move up one module in the hierarchy: + +```rust,ignore +super::client::connect(); +``` + +If we were deep in the module hierarchy, starting from the root every time +would get long. Plus, if we rearrange our modules by moving a subtree to +another place, there might be a lot of places the path would need to be updated +if we always used the path from the root. + +It would also be annoying to have to type `super::` all the time in each test, +but we now have a tool for that solution: `use`! `super::` is special and +changes the path we give to `use` so that it is relative to the parent module +instead of to the root module. + +For these reasons, in the `tests` module especially, `use super::something` is +usually the way to go. So now our test looks like this: + +Filename: src/lib.rs + +```rust +#[cfg(test)] +mod tests { + use super::client; + + #[test] + fn it_works() { + client::connect(); + } +} +``` + +If we run `cargo test` again, the test will pass and the first part of the test +result output will be: + +```bash +$ cargo test + Compiling communicator v0.1.0 (file:///projects/communicator) + Running target/debug/communicator-92007ddb5330fa5a + +running 1 test +test tests::it_works ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured +``` + +Now you know techniques for organizing your code! Use these to group related +functionality together, keep files from getting too long, and present a tidy +public API to users of your library.