Scope of a variable

So I call a database (Redis) and perform a GET command using Rust and even store the value in a variable, the problem is that the variable is inside the method block. -Not to mention the variable name is specified in the method itself and not determined when called. Is there a way where I could bring the variable out so I can use it for things while the method's return is preoccupied with Result?

pub fn get(key:String) -> redis::RedisResult<()>
{
    let client = redis::Client::open("redis://127.0.0.1/")?;
    let mut con = client.get_connection()?;
    let variable_name:String = redis::cmd("GET").arg(key).query(&mut con)?;
    println!("Value: {:?}", variable_name);
    Ok(())
}

How about returning it?

pub fn get(key: String) -> redis::RedisResult<String>
{
    let client = redis::Client::open("redis://127.0.0.1/")?;
    let mut con = client.get_connection()?;
    let variable_name = redis::cmd("GET").arg(key).query(&mut con)?;
    Ok(variable_name)
}

It almost seems to work, it returns Some("value") instead of "value" when I assign a variable to the function call.

You could .unwrap() it? If that doesn't work, you need to post a snippet and an error message

It worked! Thank you alice, you're a godsend! :smiley:

To get the result of a fallible operation, you must use either .unwrap(), the question mark, or some other method for handling the error. There's a chapter in the book about this

1 Like

Can I ask which book you're referring to? Sorry, I'm a complete novice at this.

The official Rust book, which you can find at https://doc.rust-lang.org/book/. The chapter in question is chapter nine.

Tyvm

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.