35
loading...
This website collects cookies to deliver better user experience
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
Fn = Fn-1 + Fn-2
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
Rust is installed now. Great!
cargo new rust_fibonacci
cd rust_fibonacci
main.rs
file for you, this is our entry point to Rust, open the file. It looks like this:fn main () {
println!(“Hello world”);
}
main
function that generates a fibonacci sequencefn fib (n: i32) -> i32 {
if n <= 0 {
return 0;
} else if n== 1{
return 1;
} else {
return fib (n-1) + fib(n-2);
}
}
fib
and pass variable n
as a parameter. In Rust, we have to specify the type of the parameter and its return value. I specify it’s a u32
, meaning it can only accept unsigned/positive integers of 32 bits and the ->
is specifying the return type of the function which is also a u32
integer. if
expression followed by a condition that checks if the value of n
is less or equal to 0
and returns 0
if that’s the case. We then check to see if the value of n
is 1
and return 1
. In the else
part, we implement the logic of the Fibonacci sequence by recursively calling the function with a different integer.main
function and modify it to look like this...fn main( ){
for int in 0..15 {
println! ( “fibonacci ({}) => {}”, int, fib(int));
}
}
main
function is a for loop that loops over every integer from 0 to 15 and we use the println!
to print each integer we pass and its corresponding Fibonacci value.cargo run
in your terminal and the output should look like this...main
function to look like so,use std::io;
fn main ( ) {
println! (“To quit the program type `exit` “);
loop {
println! (“TYPE A POSITIVE NUMBER”)
let mut int = String::new;
io::stdin( )
.read_line(& mut int)
.expect (“Failed to read your input”);
if int.trim( ) == “exit” {
break;
}
let int: u32 = match int.trim()
.parse() {
Ok(int) => int,
Err(_) => continue,
};
println!("Fibonacci ({}) => {}", int,
fib(int));
}
use std::io;
use
statement. main
function, we first let the user know how to quit the program by using the println! Macro to print a string to the screen.loop
keyword that will keep running until you break out by typing exit(we’ll see how that happens in a moment). We then let the user know how to interact with the game each loop by using println!
again to print a string on the screen.println! (“TYPE A POSITIVE NUMBER”);
int
let mut int = String::new;
mut
keyword when we are creating a mutable variable. (=)
is the value that int
is bound to, which is the result of calling String::new
, a function that returns a new instance of a String. So, what we are doing is creating a mutable variable that is currently bound to a new, empty instance of a String. std::io
library that we imported by calling the stdin
function from the io
module…io::stdin( )
.read_line( &mut int)
.read_line(&mut int)
, calls the read_line
method on the standard input handle to get input from the user.read_line
takes whatever the user types into standard input and append that into a string. We’re also passing one argument ( &mut int)
to the method. The &
indicates that the argument is a reference, references are also immutable by default so you need to write &mut int
to make it mutable..expect("Failed to read line");
read_line
puts what the user types into the string we’re passing it, but it also returns a value — in this case, an io::Result. The Result types are enumerations/enums. An enumeration is a type that can have a fixed set of values, and those values are called the enum’s variants.io::Result
is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect
. If this instance of io::Result
is an Ok value, expect
will take the return value that Ok
is holding and return just that value to you so you can use it.if int.trim( ) == “exit” {
break;
}
break
out of the program. The .trim( )
method is passed to eliminate any whitespace at the beginning and the end.let int: i32 = match int.trim( )
.parse ( ){
Ok (int)=> int,
Err( _ ) => continue,
}
int
, Rust allows us to shadow the previous value of int
with a new one. We often use this feature in situations in which we want to convert a value from one type to another type.int
to the expression int.trim().parse()
. The int
in the expression refers to the original int
that was a String with the input in it. The .trim()
method on a String instance will eliminate any whitespace at the beginning and end. We use the .parse()
method to turn the string into an integer. parse
returns a Result type and Result is an enum that has the variants Ok
or Err
, remember? We use a match
expression to decide what to do next based on which variant of Result that was returned. If the user typed in a number, we get Ok
and store the number in int
. If not, we call continue
and instruct the user to pass in a positive integer again. The program basically ignores all errors that parse might encounter!println!(“fibonacci({ }) => { }”, int, fib(int));
use std::io;
fn main () {
println!("To end the program, type `exit` ");
loop {
println!("Type a positive integer");
let mut int = String::new();
io::stdin()
.read_line(&mut int)
.expect("");
if int.trim() == "exit"{
break;
}
let int: u32= match int.trim()
.parse() {
Ok(int) => int,
Err(_) => continue,
};
println!("Fibonacci ({}) => {}", int, fib(int));
}
}
fn fib (n: u32) -> u32 {
if n <= 0 {
return 0;
} else if n == 1 {
return 1;
} fib(n - 1) + fib(n - 2)
}