Categories
Programming

RUST: non-exhaustive patterns: `&_` not covered pattern `&_` not covered21 sec read

Tried something like this

let a = "hello";

match a{
    "hello"=>{println!("hello")}
}

Error

non-exhaustive patterns: `&_` not covered pattern `&_` not covered

What I thought was wrong

I thought it meant you cannot match references

What the real error was

Just had to add all possibilities in match statement

let a = "hello";

match a {
    "hello" => println!("helloooooo"),
    _ => println!("blahh blahhh"),
}

 

Categories
Programming

Rust Actix web panic when using custom regex1 min read

Using Actix-web v0.7.4

Error – thread ‘arbiter:6461f87e-20ed-4848-9feb-dbe68ab5ea7e:actor’ panicked at ‘index out of bounds: the len is 1 but the index is 1’, /checkout/src/libcore/slice/mod.rs:2079:10

How I corrected it

The loop was accessing an index which didn’t exist. I don’t really know how actix web works or even how Rust works.

pub fn match_with_params  in router.rs in actix-web src was the culprit

So I changed the code to this

    /// Are the given path and parameters a match against this resource?
    pub fn match_with_params(&self, req: &Request, plen: usize) -> Option<Params> {
        let path = &req.path()[plen..];

        match self.tp {
            PatternType::Static(ref s) => if s != path {
                None
            } else {
                Some(Params::with_url(req.url()))
            },
            PatternType::Dynamic(ref re, ref names, _) => {
                if let Some(captures) = re.captures(path) {
                    let mut params = Params::with_url(req.url());
                    let mut idx = 0;
                    let mut passed = false;

                    for capture in captures.iter() {
                        if let Some(ref m) = capture {
                            if !passed {
                                passed = true;
                                continue;
                            }

                            if idx > names.len() - 1 {
                                break;
                            }

                            params.add(
                                names[idx].clone(),
                                ParamItem::UrlSegment(
                                    (plen + m.start()) as u16,
                                    (plen + m.end()) as u16,
                                ),
                            );
                            idx += 1;
                        }
                    }
                    params.set_tail(req.path().len() as u16);
                    Some(params)
                } else {
                    None
                }
            }
            PatternType::Prefix(ref s) => if !path.starts_with(s) {
                None
            } else {
                Some(Params::with_url(req.url()))
            },
        }
    }

 

Categories
Programming

Learning something new : RUST lang PART 32 min read

Error Handling

In the previous one where we built a guess the number game in rust, we did not handle any errors. The obvious error was that if something other than a number was inputted the program would crash.

Now that I have learnt how to correct this, lets change the code a little bit.

This was the code without error handling.

use std::io;

fn main() {

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;
    let mut line = String::new();

    //get user input
    stdin.read_line(&mut line).unwrap();

    //Parse input string to integer
    //Not error handled
    guess = line.trim().parse().unwrap();

}

The parse() method returns a result object. The result object would have Ok() and Err() values. So if it is OK we can run a function with the parsed value passed to it. If it is an error we can handle it gracefully and say “Listen idiot, you have to enter a number. A NUMBAAA”.

For this we use the match function or statement or whatever it is called. It seem to act like the switch statement.

So here is the update code for the number guessing game.

use std::io;

fn main() {

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;
    let mut line = String::new();

    //get user input
    stdin.read_line(&mut line).unwrap();

    //Parse input string to integer
    //Error handled 
    guess = match line.trim().parse() {
        Ok(num) => num,
        Err(_) =>{
            println!("Please enter a number");
            return;
        }
    };
}

With the loop and game –

use std::io;
extern crate rand;
use rand::Rng;

fn main() {
    //Generate a random number
    let num = rand::thread_rng().gen_range(0, 10);

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;

    while ( true ){
        let mut line = String::new();

        //get user input
        stdin.read_line(&mut line).unwrap();

        //Parse input string to integer
        //Error is handled
        guess = match line.trim().parse() {
            Ok(num) => num,
            Err(_) =>{
                println!("Please enter a number");
                continue;
            }
        };

        //If the guess is correct exit the loop
        if( guess == num ){
            println!("Correct the number was {}", guess);
            break;
        }
        else{
            println!("Wrong. Not {}", guess);
        }
    }
}

There you go rust book, I beat you at your own game.

//Also instead of using

while( true ){
    //code
}

//You could just do this

loop{
    //code
}