问题
Is there a enum/trait for owned values in general, for when you don't want to specify how exactly the value is owned (either shared or not), but you just want to own it.
I need to store references to closures in a struct, which means that they have to live as long as the struct lives. I can't copy them, of course, so they need to be references. But I don't want to make restrictions, so the user of the struct should be able to choose how they want to transfer the ownership.
This is a general problem when you can't copy the values or if they are really big.
Very general example, what I am looking for is this Owned<T>
struct Holder<T> {
value: Owned<T>,
}
...
let rc = Rc::new(variable);
let holder = Holder::new(rc.clone());
let holder2 = Holder::new(Box::new(variable2));
An example for a very easy "implementation" of this type would be:
enum Owned<T> {
Unique(Box<T>),
Shared(Rc<T>),
}
I hope I could explain what I mean.
回答1:
I think you might be a bit tripped up by the word "owns", which is understandable in Rust! Every value is owned by something, but sometimes the value refers to something that you don't own.
In your case, you just need to accept a T
. Then Holder
will own the T
:
use std::rc::Rc;
struct Holder<T> {
value: T,
}
impl<T> Holder<T> {
fn new(v: T) -> Holder<T> {
Holder { value: v }
}
}
fn main() {
let variable = "Hello world".to_owned();
let variable2 = "Hello moon".to_owned();
let rc = Rc::new(variable);
let holder = Holder::new(rc.clone());
let holder2 = Holder::new(Box::new(variable2));
}
Even if you pass a reference to Holder
, it will own the reference. It will not own the referred-to item however.
来源:https://stackoverflow.com/questions/31215418/general-way-to-own-a-value-dont-specify-rc-or-box