Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

As I can make the vector is mutable inside struct

Tags:

rust

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

like image 971
Angel Angel Avatar asked Mar 12 '23 17:03

Angel Angel


1 Answers

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
}
like image 198
malbarbo Avatar answered Mar 16 '23 01:03

malbarbo