本文介绍了因为我可以使向量在结构中是可变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我可以使向量可变

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

这是一个类似的问题但是

并且答案有效,但是如果我不想要怎么办,您可以执行此操作,应用响应链接"

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
}

这篇关于因为我可以使向量在结构中是可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:47