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"
相关推荐
毕设源码-朱学姐2 分钟前
【开题答辩全过程】以 基于spring boot的摩托车合格证管理系统为例,包含答辩的问题和答案
java·spring boot·后端
2401_832131954 分钟前
模板编译期机器学习
开发语言·c++·算法
嵌入小生0074 分钟前
Data Structure Learning: Starting with C Language Singly Linked List
c语言·开发语言·数据结构·算法·嵌入式软件
独自破碎E9 分钟前
LCR005-最大单词长度乘积
java·开发语言
2401_8384725110 分钟前
单元测试在C++项目中的实践
开发语言·c++·算法
naruto_lnq16 分钟前
移动语义与完美转发详解
开发语言·c++·算法
毕设源码-赖学姐20 分钟前
【开题答辩全过程】以 基于spring boot的国学诗词网站设计与实现--为例,包含答辩的问题和答案
java·spring boot·后端
梦想画家22 分钟前
掌控并发的灵魂:Go context 从入门到实战全解析
开发语言·golang
yunsr34 分钟前
python作业1
开发语言·python·算法
赤水无泪41 分钟前
04 C++语言---运算符和符号
开发语言·c++