Ask coding questions

← Back to all posts
Why wont this work
JacobMcPherson1 (207)

Why the heck wont this work EEE

Answered by MocaCDeveloper (594) [earned 5 cycles]
View Answer
Comments
hotnewtop
MocaCDeveloper (594)

There is a trailing new line.

So, on line 13, I figured this would be a easier way to convert from the string to an int, and remove the new line:

let new_num = number.trim().parse::<i64>().unwrap();

Now you can remove use std::str::FromStr and use the .parse method to parse the string into the type of i64.
The .trim() method just removes the trailing whitespace/newline.

Your code should now look like:

use std::io;

fn main() {
  fn fib(num: i64) -> i64 {
    if num <= 1 {
      return num;
    }
    return fib(num - 1) + fib(num - 2);
  }
  let mut number = String::new();
  println!("How many digits do you want in the fib sequnce: ");
  io::stdin().read_line(&mut number).expect("Failed to read line");
  let new_num = number.trim().parse::<i64>().unwrap();
  let mut i = 1;
  while i < new_num {
      println!("{}", fib(i));
      i += 1
  }
}

P.S: I'd highly advice to declare the function declared in the main function outside of the main function. There is no use to having nested functions with such a simple program.

So, a more standard way to approach this program:

use std::io;

fn fib(num: i64) -> i64 {
    if num <= 1 {
      return num;
    }
    return fib(num - 1) + fib(num - 2);
}

fn main() {
  let mut number = String::new();
  println!("How many digits do you want in the fib sequnce: ");
  io::stdin().read_line(&mut number).expect("Failed to read line");
  let new_num = number.trim().parse::<i64>().unwrap();
  let mut i = 1;
  while i < new_num {
      println!("{}", fib(i));
      i += 1
  }
}

Is by not having nested functions.

MocaCDeveloper (594)

@JacobMcPherson1

If you have any more questions don't hesitate to ask!

I write Rust as my own personal language just for side projects and what not. I have just started learning it but man is it a fun language to learn. I am going to slowly progress into making some pretty interesting projects in it.

So, if you have any questions, don't hesitate to ask. I have rapidly grew in the language in a matter of 2 weeks!