blackbeam / rust-mysql-simple

Mysql client library implemented in rust.
Apache License 2.0
663 stars 144 forks source link

Example code does not work for me #314

Closed conormdowney closed 2 years ago

conormdowney commented 2 years ago

Im just trying to run the simple example to connect to a database but im getting an error on the line trying to create a new Pool. Here is my code

use mysql::*;
use mysql::prelude::*;

fn main() {
    println!("Hello, world!");
    let url = "db-string";
    let pool = Pool::new(url)?;
}

Im getting an error on the last line. it says:

error[E0277]: the trait bound `Opts: From<&str>` is not satisfied
   --> src/main.rs:7:26
    |
7   |     let pool = Pool::new(url)?;
    |                --------- ^^^ the trait `From<&str>` is not implemented for `Opts`
    |                |
    |                required by a bound introduced by this call

Im pretty new to rust so can someone help me with this?

blackbeam commented 2 years ago

@conormdowney, hi. Sorry, but looks like the example code wasn't properly updated. Following code should work:

use mysql::*;
use mysql::prelude::*;

fn main() {
    println!("Hello, world!");
    let opts = Opts::from_url("db-string")?;
    let pool = Pool::new(opts)?;
}
conormdowney commented 2 years ago

Thanks for the update. Im getting a different error now with the code you gave me:

fn main() {
5  | |     println!("Hello, world!");
6  | |     let opts = Opts::from_url("db-string")?;
7  | |     let pool = Pool::new(opts)?;
   | |                               ^ cannot use the `?` operator in a function that returns `()`

If i unwrap() instead of the use the ? it works though. just in case any other newbie runs into this issue.

blackbeam commented 2 years ago

This one already answered here.

conormdowney commented 2 years ago

Thats cool. thanks. I am curious though, and i realise this isnt really the place for this but hoping you wont mind, for Pool::new, its return type is Result. Why not Result<Pool, Error>. If something goes wrong there it still expects a Pool back, correct?

blackbeam commented 2 years ago

This result is just a type alias to std::result::Result defined here: https://github.com/blackbeam/rust-mysql-simple/blob/6d856627425a19a854f13324bb6cdc93f7eb857e/src/error/mod.rs#L350

It's a usual practise for libraries and modules to define it's own type aliases to Result (eg std::Io::Result, std::fmt::Result)

conormdowney commented 2 years ago

okay. cool. Im still wrapping my head around error handling in Rust. If I was to do a match on the result (not necessary I know) then I would need the Error to return the appropriate type. This issue is fixed though so ill close it. Thanks