Can this Rust code be written without a match statement?

linuxfood created bindings for sqlite3 , for which I am grateful. I'm just starting to learn Rust (0.8), and I'm trying to figure out what this bit of code does:

extern mod sqlite;

fn db() {

    let database =
        match sqlite::open("test.db") {
            Ok(db) => db,
            Err(e) => {
                println(fmt!("Error opening test.db: %?", e));
                return;
            }
        };

I really understand what he is doing. It tries to get a database connection and also checks for an error. I do not understand how this is done.

To better understand this, I wanted to rewrite it without instructions match, but I have no knowledge for this. Is it possible? Does it return sqlite::open()two variables or only one?

How can this example be written in different ways without instruction match? I am not saying that this is necessary or preferable, but it can help me learn the language.

+4
4

, database. sqlite::open, , , Result<T, E> ( Ok(T) Err(E)). , Ok, , db ( database). , Err, , , .

( , - ):

let res = sqlite::open("test.db");
if res.is_err() {
    println!("Error opening test.db: {:?}", res.unwrap_err());
    return;
}
let database = res.unwrap();
+6

open SqliteResult<Database>; pub type SqliteResult<T> = Result<T, ResultCode>, std::result::Result<Database, ResultCode>.

Result enum, : , . , , .

, , is_err, ( , ):

fn is_err(&self) -> bool {
    match *self {
        Ok(_) => false,
        Err(_) => true,
    }
}

unwrap ( ):

fn unwrap(self) -> T {
    match self {
        Ok(t) => t,
        Err(e) => fail!(),
    }
}

, . , , .

+4

sqlite::open() Enum. , .
. http://static.rust-lang.org/doc/0.8/tutorial.html#enums

, SqliteResult Ok, Err, Ok, db, Err, .

# Java SqliteResult , Ok Err, . match , , . , , , .

+3

Rust , .

if let Ok(database) = sqlite::open("test.db") {
    // Handle success case
} else {
    // Handle error case
}

if let.

+3

All Articles