rust-lang / book

The Rust Programming Language

Home Page:https://doc.rust-lang.org/book/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unclear approach to first_word function

mguzy opened this issue · comments

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • first_word
  • I have checked the latest main branch to see if this has already been fixed, in this file:
    • yes

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:
I am a rust noobie (just started going thru your book) with background in other languages. Slices chapter starts with following problem:

Here’s a small programming problem: write a function that takes a string of words separated by spaces and returns the first word it finds in that string. If the function doesn’t find a space in the string, the whole string must be one word, so the entire string should be returned.

After what I learned in previous lesson my initial though was to write something like:

fn first_word(sentence: &String) -> String {
    let mut result = String::from("");
    for ch in sentence.chars() {
        if ch == ' ' {
            return result
        } else {
            result.push(ch);
        }
    }
    return result
}

It is not really clear to me why proposed function tries to return index instead of first word.

Suggested fix:
Maybe fix is not requried and I just don't get it, otherwise to make it clear that we do not want a new string containing the first word.

Thanks for opening this, @mguzy! In this case, if you keep reading, the rest of the chapter will get you to the answer you are looking for—ultimately, it returns a slice of the original string, which just a reference to a subset of that original, and does not create a new string. The chapter also explains why that might be important: it does not need to create a new string in memory, so it can be much less expensive. Hopefully that helps answer your immediate question!

There is always a tradeoff with this kind of thing in teaching: do you jump straight to the “right” answer or build up to it gradually? In this chapter, the book builds up to it gradually. Closing this accordingly. Thanks, and good luck with your Rust learning!

Thanks for quick answer @chriskrycho!