Rust-clippy: Recursion lint

Created on 1 Nov 2015  路  2Comments  路  Source: rust-lang/rust-clippy

Although recursion isn't bad in and of itself, it can often lead to infinite loops. Also some companies don't allow their programmers to use recursion (See this well known paper by NASA).
Jonathan Blow implemented a similar lint for his new programming language in this video.
This lint should probably be allow by default, because in most cases recursion is fine to use.

E-medium L-lint T-middle

Most helpful comment

direct recursion should already be caught by rustc: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0c6c409030e91d68f66607292b736332

warning: function cannot return without recursing
 --> src/lib.rs:8:5
  |
8 |     pub fn a_field(&self) -> &[Something] {
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing
9 |         &self.a_field()
  |          -------------- recursive call site
  |
  = note: #[warn(unconditional_recursion)] on by default
  = help: a `loop` may express intention better if this is on purpose

All 2 comments

I guess this issue has not been solved because it is quite complex to do.
There is however a simple pattern that may be detected without too much difficulties (I personnaly do quite often this mistake):

struct MyStruct {
 a_field: Vec<Something>
}

impl MyStruct {
 pub fn a_field(&self) -> &[Something] {
   &self.a_field()
 }
}

instead of

struct MyStruct {
 a_field: Vec<Something>
}

impl MyStruct {
 pub fn a_field(&self) -> &[Something] {
   &self.a_field
 }
}

direct recursion should already be caught by rustc: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0c6c409030e91d68f66607292b736332

warning: function cannot return without recursing
 --> src/lib.rs:8:5
  |
8 |     pub fn a_field(&self) -> &[Something] {
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing
9 |         &self.a_field()
  |          -------------- recursive call site
  |
  = note: #[warn(unconditional_recursion)] on by default
  = help: a `loop` may express intention better if this is on purpose
Was this page helpful?
0 / 5 - 0 ratings