Puzzle 23Constant Loops
 const​ ​fn​ ​fib​(n: u128) ​->​ u128 {
 let​ ​mut​ a = 1;
 let​ ​mut​ b = 1;
 for​ _ in 2..n {
 let​ tmp = a + b;
  a = b;
  b = tmp;
  }
  b
 }
 
 fn​ ​main​() {
 for​ i in 0..5 {
  println!(​"Fib {} = {}"​, i, ​fib​(i));
  }
 }

Guess the Output

images/aside-icons/important.png

Try to guess what the output is before moving to the next page.

images/hline.png

The program will fail to compile with the following error message:

 'for' is not allowed in a 'const fn'

Discussion

Marking a function as const causes the function to run at compile ...

Get Rust Brain Teasers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.