As I can make the vector is mutable inside struct

前端 未结 1 1882
庸人自扰
庸人自扰 2021-01-13 17:01

As I can make the vector is mutable

pub struct Test<\'a>{
    vec: &\'a mut Vec,
}
impl<\'a> Test<\'a> {
    pub fn created         


        
1条回答
  •  北海茫月
    2021-01-13 17:27

    Maybe you are looking for interior mutability. Please, do not use interior mutability loosely, read this first.

    use std::cell::RefCell;
    
    pub struct Test{
        vec: RefCell>,
    }
    
    impl Test {
        pub fn created()->Test {
            Test {vec: RefCell::new(Vec::new()) }
        }
        pub fn add(&self, value: i32){  
            self.vec.borrow_mut().push(value);
        }
    }
    
    fn main() {
        let test = Test::created();
        test.add(1i32);
    
        let test1 = Test::created();
        // test1 = test; // does not work anymore
    }
    

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