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"
相关推荐
gugucoding14 分钟前
2. 【Java】搭建Java开发环境
java·开发语言
多加点辣也没关系14 分钟前
JavaScript|第9章:对象 — 基础
开发语言·javascript·ecmascript
2601_9498180921 分钟前
Vector从入门到应用(C++ STL动态数组万字全解
开发语言·c++
汤米粥1 小时前
Python爬虫中Xpath用法之——normalize-space()
开发语言·python
doiito1 小时前
【Agent Harness】Gliding Horse v0.1.4.preview 发布:时间感知、闭环审计与智能增强
ai·rust·架构设计·系统设计·ai agent
IguoChan1 小时前
4. d2l — 模型选择、欠拟合和过拟合
后端
科技道人1 小时前
记录 设置-显示大小和字体
开发语言·android设置·字体和显示大小
浮江雾1 小时前
Flutter第三节----Dart中的数据类型
android·开发语言·学习·flutter·入门·函数
weixin_422329311 小时前
AgentScope Java 项目入门 & Builder 深度解读
java·开发语言·人工智能
shepherd1262 小时前
一次把 Spring MVC 文件上传参数“查没了”的排查:multipart、Filter 与 request body 的连环坑
java·后端·spring·mvc