book
book copied to clipboard
The book should state _why_ ownership is not wanted in the example
URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch04-03-slices.html
Description of the problem: After the first code block, the following text is written:
The first_word function has a &String as a parameter. We don’t want ownership, so this is fine.
I don't understand why in that case ownership is not required / wanted
Suggested fix: Add a short explanation
It's simple as: A reference & is not an owner.
I suggest you to re-read the following carefully:
https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html
I see why you stumbled over this! However, the book answers your question if you keep reading: we don’t want ownership here because we want to get an answer about this string without moving it away from the original function, so that we can continue using the string in the original function:
let s = String::from("hello world");
let word = first_word(&s);
// other things with `s`, as shown in the rest of the section
Remember from 4.01: What is Ownership? that if we moved it into the first_word function, it would get dropped at the end of that function:
fn first_word(s: String) {
// if we don’t do anything else, `s` gets dropped when we return!
}
The only way to avoid that would be to also return it from that function. You could imagine writing a signature like first_word(s: String) -> (String, &str), where you return the original string when you’re done as well as a reference to it… but this is actually not legal Rust, because Rust doesn’t have a way to relate the reference to the thing it’s referencing in that case.
All that to say: the rest of the example shows why we don’t need or want ownership of the string. We don’t want to try to stop and explain all of this at the point where the statement is made, because it becomes clear by continuing to read the rest of the section.
I mean stating the reason right there would make it much more understandable and not harm anyone, right? I'll make a proposal
https://github.com/rust-lang/book/pull/4074