Why does the Rust Book (only) teach imperative programming?


In chapter 12 the excellent rust book shows how to implement the search function in an imperative way:

fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {


In my opinion this much harder to understand than the following “functional” alternative which emphasizes the “what” (filter matching lines) instead of the “how” (use a mutable variable, use a loop, use a condition, etc.):

fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    contents.lines().filter(|line| line.contains(query)).collect()

I’d be interested in understanding the reasons behind this bias towards imperative programming. Is it because the authors assume the readers are more familiar with imperartive code? Or are the authors themselves more familiar with this approach? Anything else?

1 Like


Chapter 13 (i.e. the one after this example) is called ‘Functional Language Features’, and that’s where iterators are introduced. I presume they didn’t want to use these features until the chapter that shows you how they work/how to use them.

In fact, later in Chapter 13 they update that exact example to use iterators :slight_smile:



As one of the co-authors of this text, you’re correct! There’s one more reason though, and it’s sort of the same thing, but in reverse. In order to motivate the new feature, it’s often good to show something right before it that it can make better. So in some sense, this example was picked because updating it to the functional way is pretty much completely better in every way.



Thanks a lot, @17cupsofcoffee and @steveklabnik, for your quick replies. I think I will defer further questions until I have read the whole book :wink:

Actually I think the approach chosen – starting out with something that can be improved later – is a really good one. Do you think it might make sense to add a short comment – like in other places, e.g. when introducing iterators for the implementation of search – that in a later chapter a different and better (is it really better?) approach is shown?



Another excellent strategy for keeping readers actively engaged is to raise questions in their mind, and then after they have thought of the question themselves, answer it. If you anticipate everything your readers will wonder before they wonder it, you risk turning them into passive consumers, and they won’t learn as well.

For that reason, I don’t think a prefatory comment would actually help the goals of that particular section.