Lifetime params for more complex function returns

Apologies, newbie here (thanks, edited formatting)

I'm querying some Mysql, which is working when I have a value with

    use mysql::*;
    use mysql::prelude::*;
    ..
    let mut row = result_set.as_ref().unwrap();
    let tag_string: <String> = row.get(4).unwrap();
Cargo.toml has mysql = "18.2.0"  

, but I'm getting a panic when I try to cater for a Null sql value, so trying to use get_opt() instead.

Looking at the rust mysql docs here it seems to shows

 pub fn get_opt<T, I>(&self, index: I) -> Option<Result<T, FromValueError>>

However, if I use

let tag_string: Option<Result<String>> = row.get_opt(4);

I get

expected enum `mysql::error::Error`, found struct `mysql_common::value::convert::FromValueError

If I try

let tag_string: Option<Result<String, FromValueError >> = row.get_opt(4);

I get

FromValueError:  unexpected type argument

and

expected enum `mysql::error::Error`, found struct `mysql_common::value::convert::FromValueError

I've also tried giving it one mysql::error::Error or FromValueError only argument, but again I get

expected enum `mysql::error::Error`, found struct `mysql_common::value::convert::FromValueError

So I'm a bit confused about the error types and how to declare that type when it's only looking for one parameter ?

You can read more about formatting here, and note that you can edit the post.

Thanks, have edited.

Can I ask you to use code blocks for the rest of the post as well instead of just marking the line as code with a single backtick?

As for your question, the purpose of get_opt is not to handle null values, but to handle values that have been taken using Row::take. To handle a null value, use get with T = Option<Something>.

let tag_string: Option<String> = row.get(4).unwrap();

Aha thanks, that did it.

You may also consider using take instead of get, as it avoids some unnecessary copying.

1 Like

Thanks, I had previously tried that, but had got an error...

`row` is a `&` reference, so the data it refers to cannot be borrowed as mutable

But I think that's likely a separate problem with my lack of understanding passing references.

To avoid the copying, the call to take removes the value from the row, meaning that it can only be taken once (hence why get_opt returns a Result). This modifies the Row, so you must use a mutable reference.

Thanks Alice, much appreciate the help.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.