因为我可以使vector在struct中是可变的

时间:2016-04-04 21:37:51

标签: rust

因为我可以使载体变得可变

pub struct Test<'a>{
    vec: &'a mut Vec<i32>,
}
impl<'a> Test<'a> {
    pub fn created()->Test<'a>{
        Test {vec: &'a mut Vec::new() }
    }
    pub fn add(&self, value: i32){  
        self.vec.push(value);
    }
}
expected `:`, found `mut`
Test {vec: &'a mut Vec::new() }
               ^~~

这是similar question

并且答案有效,但如果我不想要,你可以这样做,“应用响应链接”

pub struct Test{
    vec: Vec<i32>,
}
impl Test {
    pub fn created()->Test {
        Test {vec: Vec::new() }
    }
    pub fn add(&mut self, value: i32){  
        self.vec.push(value);
    }
}
..//
let mut test: my::Test = my::Test::created();
test.add(1i32);

let mut test1: my::Test = my::Test::created();

test1 = test; <-- I do not want, you can do this
..//

因为我可以使矢量是可变的,而不是使它成为所有的结构

1 个答案:

答案 0 :(得分:4)

也许您正在寻找interior mutability。请不要松散地使用内部可变性,首先阅读this

use std::cell::RefCell;

pub struct Test{
    vec: RefCell<Vec<i32>>,
}

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
}