General way to own a value (don't specify `Rc` or `Box`)

后端 未结 1 1622
清酒与你
清酒与你 2021-01-21 08:17

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 i

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 08:36

    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 {
        value: T,
    }
    
    impl Holder {
        fn new(v: T) -> Holder {
            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.

    0 讨论(0)
提交回复
热议问题