寻找与 Rust 中的 Cell 完全相反的用例——内部不变性?

问题描述 投票:0回答:2

我学到了很多关于

Cell<T>
的知识,它非常有用,但我目前有一个类似

的结构
struct User {
    username: String,
    pronouns: Cell<Option<Pronouns>>,
    email: Cell<Option<String>>
}

以及更多使用

Cell<T>
的字段。正如您所看到的,这个结构中的几乎每个字段除了用户名都是通过使用 Cell 进行内部可变的,现在我想知道是否有一些东西允许完全相反的方法所以我不知道必须在 Cell 中包装几乎每一个
User
的字段。像这样的东西:

struct User {
    username: AntiCell<String>,
    pronouns: Option<Pronouns>,
    email: Option<String>
}

// Created users will be mutable.

现在,使用一百万个

Cell
s 是完全没问题的,但我想知道这里是否有某种方法可以照顾到少数人。

oop rust struct field immutability
2个回答
0
投票

这个要求真的没有意义。

假设您有一个 不可变 引用,指向一个

User
类型的值。在这里,您可以修改包含在
Cell
中的字段,但不能修改没有包含的字段。所以在这种情况下你不需要
AntiCell

现在假设您有一个 mutable 引用。是的,你可以改变所有字段,但即使

AntiCell
存在也是如此:

struct User {
    username: AntiCell<String>,
    pronouns: Option<Pronouns>,
    email: Option<String>
}

fn foo(user: &mut User) {
    *user = User {
        // replace the immutable field with a new value
        username: AntiCell::new(String::from("Something else")),
        // move the remaining mutable fields from the original
        ..user
    };
}

只要您对某个值具有可变访问权限,就可以更改其中的任何一个或全部。


0
投票

如果你想减少

Cell
的数量,你可以将其他字段移动到另一个结构中:

struct User {
    username: String,
    details: Cell<Details>,
}

struct Details {
    pronouns: Option<Pronouns>,
    email: Option<String>
}
© www.soinside.com 2019 - 2024. All rights reserved.