如何仅使某些结构字段可变? [英] How can I make only certain struct fields mutable?

查看:45
本文介绍了如何仅使某些结构字段可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构:

pub struct Test {
    pub x: i32,
    pub y: i32,
}

我想要一个可以改变这个的函数——简单:

I'd like to have a function that mutates this — easy:

pub fn mutateit(&mut self) {
    self.x += 1;
}

这使得整个结构体在 mutateit 的函数调用期间都是可变的,对吗?我想改变x,我不想改变y.有什么办法可以可变地借用 x 吗?

This makes the entire struct mutable for the duration of the function call of mutateit, correct? I only want to mutate x, and I don't want to mutate y. Is there any way to just mutably borrow x?

推荐答案

引用 :

Rust 不支持语言级别的字段可变性,所以你不能这样写:

Rust does not support field mutability at the language level, so you cannot write something like this:

struct Point {
    mut x: i32, // This causes an error.
    y: i32,
}

您需要内部可变性,这在标准中有很好的描述文档:

You need interior mutability, which is nicely described in the standard docs:

use std::cell::Cell; 

pub struct Test {
    pub x: Cell<i32>,
    pub y: i32
}

fn main() {
    // note lack of mut:
    let test = Test {
        x: Cell::new(1), // interior mutability using Cell
        y: 0
    };

    test.x.set(2);
    assert_eq!(test.x.get(), 2);
}

而且,如果您想将其合并到一个函数中:

And, if you wanted to incorporate it in a function:

impl Test {
    pub fn mutateit(&self) { // note: no mut again
        self.x.set(self.x.get() + 1);
    }
}

fn main() {
    let test = Test {
        x: Cell::new(1),
        y: 0
    };

    test.mutateit();
    assert_eq!(test.x.get(), 2);
}

这篇关于如何仅使某些结构字段可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆