How to convert & Vector <Mutex> to Vector <Mutex>

I am working on the Rust sample. There is this piece of code:

fn new(name: &str, left: usize, right: usize) -> Philosopher {
    Philosopher {
        name: name.to_string(),
        left: left,
        right: right,
    }
}

      

What's the best way to adapt this to a vector? It works:

 fn new(v: Vec<Mutex<()>>) -> Table {
    Table {
       forks: v
    }
 }

      

Than I've tried the following:

fn new(v: &Vec<Mutex<()>>) -> Table {
     Table {
         forks: v.to_vec()
     }
 }

      

But this gives me:

the trait `core::clone::Clone` is not implemented 
for the type    `std::sync::mutex::Mutex<()>` 

      

Which makes sense. But what should I do if I want to pass a link to a table and don't want to store the link inside the table structure?

+3


source to share


1 answer


The error message actually explains a lot here. When you call to_vec

on &Vec<_>

, you must clone the entire vector. This is because it Vec

owns the data and the link is not specified. To clone a vector, you must clone the entire content as well. This is because the vector owns all the elements within it.

However, your vector contains Mutex

, which cannot be cloned. A mutex is a unique access to some data, so having two separate mutexes for the same data would be meaningless.



Instead, you probably want to share the links to the mutexes rather than clone them entirely. Most likely you want Arc

:

use std::sync::{Arc, Mutex};

fn main() {
    let things = vec![Arc::new(Mutex::new(()))];
    things.to_vec();
}

      

+8


source







All Articles