7

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
  • 19,670
  • 29
  • 79
  • 105

1 Answers1

10

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
}
malbarbo
  • 10,717
  • 1
  • 42
  • 57
  • thanks for your time, and the recommendation of the link for this case – Angel Angel Apr 19 '16 at 14:28
  • The book link is pretty old and it links to a section of the new book that doesn't discuss "interior mutability"; I think you'll want https://doc.rust-lang.org/book/ch15-05-interior-mutability.html – Carl Walsh Aug 24 '22 at 16:10