Reputation: 3
I would like to have a cloneable struct with a type parameter that is uncloneable used for a field that is of type Arc. It looks like Rust requires all type parameters for a cloneable struct to be cloneable too. Without a type parameter, it is possible to declare a cloneable struct with an uncloneable field that is an Arc.
Here is the code that shows:
I think it is unnecessary to require the type parameter to be cloneable if it is used in a field that is an Arc<> of that type.
My specific case is a multi threaded pool of resources - I do not want to require my resource to be cloneable. The pool uses Arc<Mutex<Vec<T>>>
as a way to store resources. Is there a way to make the pool cloneable and keep the T uncloneable.
Is the solution to manually implement clone()
method and not use #[derive(Clone)]
?
use std::sync::Arc;
use std::clone::Clone;
#[derive(Clone)]
struct ContainerWithGenerics<T> {
contained: Arc<T>
}
#[derive(Clone)]
struct ValueCloneable {
value: i32
}
#[derive(Clone)]
struct ContainerWithoutGenerics {
contained: Arc<ValueNotCloneable>
}
struct ValueNotCloneable {
value: i32
}
fn main() {
let container0 = ContainerWithGenerics { contained: Arc::new(ValueCloneable { value: 1i32 }) }.clone();
let container1 = ContainerWithoutGenerics { contained: Arc::new(ValueNotCloneable { value: 1i32 }) }.clone();
}
Upvotes: 0
Views: 31