5

As I can make the vector is mutable

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() }
               ^~~

This is a similar question but

and the answer works, but what if I do not want, you can do this, "applying the response link"

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
..//

as I can make the vector is mutable, without making it be all the struct

Community
  • 1
  • 1
Angel Angel
  • 16,564
  • 27
  • 71
  • 101

1 Answers1

7

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<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
}
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
malbarbo
  • 9,909
  • 1
  • 35
  • 53