Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to borrow mutable value?

I’ve been trying to separate all my Redis operations in a separate implementation, but I got this error when I passed the Redis reference to the implementation.

error[E0596]: cannot borrow `*self.redis_client` as mutable, as it is behind a `&` reference
  --> src/main.rs:30:21
   |
30 |         let _: () = self.redis_client.set("key", "value").unwrap();
   |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

Code:

use redis::{Commands};
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let redis_client_uri = String::from("redis://127.0.0.1:6379");
    let redis_client = redis::Client::open(redis_client_uri)?;
    let mut redis = redis_client
        .get_connection()
        .expect("Failed to connect redis");

    let batch = vec!["Sample value".to_string()];
    CacheOperations::new(&redis, batch);
    Ok(())
}

struct CacheOperations<'a> {
    redis_client: &'a redis::Connection,
    batch: Vec<String>,
}

impl<'a> CacheOperations<'a> {
    fn new(redis_client: &'a redis::Connection, batch: Vec<String>) -> Self {
        Self {
            redis_client: &redis_client,
            batch: batch,
        }
    }

    fn insert_batch(self) {
        let _: () = self.redis_client.set("key", "value").unwrap();
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to use the mut keyword to indicate that a reference or value is mutable. When you use it with a lifetime, the mut goes after the lifetime usage (Ex: &'abc mut x).

use redis::{Commands};
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let redis_client_uri = String::from("redis://127.0.0.1:6379");
    let redis_client = redis::Client::open(redis_client_uri)?;
    let mut redis = redis_client
        .get_connection()
        .expect("Failed to connect redis");

    let batch = vec!["Sample value".to_string()];
    // Use a mutable reference when creating the CacheOperations
    CacheOperations::new(&mut redis, batch);
    Ok(())
}

struct CacheOperations<'a> {
    // Store a mutable reference
    redis_client: &'a mut redis::Connection,
    batch: Vec<String>,
}

impl<'a> CacheOperations<'a> {
    // We need to consume a mutable reference
    fn new(redis_client: &'a mut redis::Connection, batch: Vec<String>) -> Self {
        // No need to reference the reference, we can store it as-is
        Self { redis_client, batch }
    }

    // While not required here, you can use mut self to state that self is mutable 
    // when a function consumes self as an owned value.
    fn insert_batch(mut self) {
        let _: () = self.redis_client.set("key", "value").unwrap();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading