gpt4 book ai didi

rust - 因为我可以使向量在结构内部可变

转载 作者:行者123 更新时间:2023-11-29 07:57:39 25 4
gpt4 key购买 nike

因为我可以使向量可变

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

这是一个 similar question但是

答案有效,但如果我不想要怎么办,您可以这样做,“应用响应链接”

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

因为我可以使向量可变,而无需将其全部设为结构

最佳答案

也许您正在寻找interior mutability .请不要随意使用内部可变性,请阅读 this首先。

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
}

关于rust - 因为我可以使向量在结构内部可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36413364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com