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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With