How to initialize mysql in or from main()?

I'm learning Rust, coming from Go. I'm still trying to wrap my head around some basic concepts, so apologies for what's probably a stupid question!

I want to 1. Connect to a MySQL instance and 2.) Make a query, then 3.) Parse result into Vec<Struct>

I don't understand why I can't do stuff in main without Rust complaining.

Code sample:

use mysql::{Pool};
use std::error::Error;
use mysql::prelude::Queryable;

extern crate rawsql;
extern crate mysql;

fn main() -> Result<(), Box<dyn Error>> {
    let pool = Pool::new("mysql://root:mysql@127.0.0.1:33061/ebdb")?;
    let mut conn =  pool.get_conn()?;
    let orgs = conn
        .query_map(
            "SELECT customer_id, amount, account_name from payment",
            |(id, name, country)| {
                Organization { id, name, country }
            },
        )?;

    // How do I print the orgs here?
}

#[derive(Debug, PartialEq, Eq)]
pub struct Organization {
    pub id: Option<i32>,
    pub name: String,
    pub country: String
}

This results in

--> src/main.rs:8:14
|
8 | fn main() -> Result<(), Box<dyn Error>> {
|    ----      ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found `()`
|    |
|    implicitly returns `()` as its body has no tail or `return` expression
|
= note:   expected enum `std::result::Result<(), Box<(dyn StdError + 'static)>>`
        found unit type `()`

I'm just testing out the language and there's something here I don't get. What do I "return" from fn main if I want to.. do stuff in fn main without the compiler complaining? :smile:

How do I iterate through the result of Vec<Organization> at the last line?

Add an Ok(()) at the end of main to fix the error. You can iterate with

for thing in orgs {
    ...
}

Aaaa it works, thank you! My sanity is restored :smiley:

In Rust the last expression in a function's body is returned to the caller. When an expression ends with a ; (i.e. it is a statement), that statement will evaluate to "nothing" (the empty tuple () in Rust parlance).

So now you've said your main() function will return a Result<(), Box<dyn Error>>, but it's returning () (that's the whole "expected Result<...> found unit type" in the error message). Because the function is returning successfully, I'd add a trailing Ok(()) after your last statement.

1 Like