rust中结构体的属性默认是不能修改的,要想修改可以有两种方式

Rust中结构体里面的属性默认是不支持修改的,而且默认不是pub的,要想修改的话,有两种方式,我以为和python里面的类似呢,但是还是需要一点技术含量的。如果想在引到外部修改,需要声明pub,如果想在impl中实现,需要将self参数修改为&mut self。

第一种在impl中修改

需要声明self为可变引用,然后通过在impl中使用self修改

rust 复制代码
pub struct React {
    width: String,
    height: String,
}



impl React {
    pub fn new(w: String, h: String) -> Self {
        React { width: w, height: h }
    }

    pub fn set_height(&mut self, h: String) {
        self.height = h;
    }
}

修改的时候,直接创建实例对象,然后调用set_height方法:

rust 复制代码
    // 创建结构体
    let mut r = React::new(String::from("2"), String::from("3"));
    r.set_height(String::from("10000"));

修改后的结果:

rust 复制代码
warning: `day4` (bin "day4") generated 3 warnings
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/day4`
React height is:"10000"

第二种声明pub

声明pub后,再使用 . 属性的方式直接修改:

rust 复制代码
pub struct React {
    pub width: String,
    pub height: String,
}



let mut r = React::new(String::from("2"), String::from("3"));
// r.set_height(String::from("10000"));
r.height = String::from("6666");

修改后的结果:

rust 复制代码
warning: `day4` (bin "day4") generated 2 warnings
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/day4`
React height is:"6666"
相关推荐
CreasyChan9 小时前
C#特性(Attributes)详解
开发语言·c#
历程里程碑9 小时前
C++ 9 stack_queue:数据结构的核心奥秘
java·开发语言·数据结构·c++·windows·笔记·算法
tirelyl9 小时前
LangChain.js 1.0 + NestJS 入门 Demo
后端
csbysj20209 小时前
JavaScript AI 编程助手
开发语言
王中阳Go背后的男人9 小时前
GoFrame vs Laravel:从ORM到CLI工具的全面对比与迁移指南
后端·go
t198751289 小时前
基于MATLAB的线性判别分析(LDA)降维算法实现方案
开发语言·算法·matlab
weixin_462446239 小时前
nodejs 下使用 Prettier 美化单个 JS 文件(完整教程)
开发语言·javascript·ecmascript
醇氧9 小时前
【Windows】从守护到终结:解析一个 Java 服务的优雅停止脚本
java·开发语言·windows
reasonsummer9 小时前
【办公类-18-07】20251215(Python)“口腔检查涂氟信息”批量生成打印(区名、学号、姓名、学校、班级、身份证、户籍、性别、民族)
开发语言·python
小鹿学程序9 小时前
FileZilla连接到虚拟机
java·服务器·开发语言