0

In the rust rust book, the section on improving with iterators demonstrates putting iterator adapaters on a separate line like so:

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

By default, rustfmt consolidates these to a single line. I cannot find a place in the documentation to prevent this. How can one do so?

Screenshot: enter image description here

Darkenor
  • 4,349
  • 8
  • 40
  • 67
  • I don't see the book recommend anything about formatting style from the chapter you linked. – kmdreko Feb 24 '23 at 21:05
  • It's in the web page that way and I added a screenshot to show it. Also, if you copy any of the code samples with it that way then you will see that the code is on a separate line by intention. It would seem strange to have the code be something other than rust standard in the official book. – Darkenor Feb 24 '23 at 21:10
  • 1
    Oh I thought you were saying "the book recommends newlines between methods", but you're really saying "the book puts methods on new lines, so it must be the recommended way", right? – kmdreko Feb 24 '23 at 21:13
  • Yes, that's correct. I suppose a better verb would have been "demonstrates." I will update it. – Darkenor Feb 24 '23 at 21:20

1 Answers1

2

Whether method chains are formatted on one line or multiple is primarily governed by the chain_width property:

Maximum width of a chain to fit on one line.

  • Default value: 60
  • Possible values: any positive integer that is less than or equal to the value specified for max_width
  • Stable: Yes

By default this option is set as a percentage of max_width provided by use_small_heuristics, but a value set directly for chain_width will take precedence.

rustfmt doesn't know about types, so it treats all method calls the same. You can reduce chain_width manually in rustfmt.toml to encourage it to use new lines more often.

That being said, the default width is 60, and the full expression shown here is 62 at least, so I don't know why it would format in a single line for you. When I use rustfmt with the default config it leaves the formatting exactly as shown; on new lines.

kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • I am willing to bet I have something misconfigured. I saw that property and thought it wasn't related to that due to the width. Thanks for confirming. – Darkenor Feb 24 '23 at 21:41