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 分钟前
学JavaWeb第七天——yml配置文件 & 后端实战Tlias案例
java·开发语言·spring
AI科技星3 分钟前
空间光速螺旋动力学:统一质量、引力、电磁与时空本源的公理化理论与全现象验证
c语言·开发语言·opencv·算法·r语言
BUG?不,是彩蛋!3 分钟前
AI智慧社区--实现修改密码、退出登录、动态路由
java·spring boot·后端·intellij-idea·mybatis
smxgn4 分钟前
【SpringBoot整合系列】SpringBoot3.x整合Swagger
java·spring boot·后端
qq_404265834 分钟前
C++中的代理模式实战
开发语言·c++·算法
liuyao_xianhui7 分钟前
动态规划_最大子数组和_C++
java·开发语言·数据结构·c++·算法·链表·动态规划
焦糖玛奇朵婷10 分钟前
盲盒抽卡机小程序搭建,探索卡牌市场
大数据·开发语言·程序人生·小程序·软件需求
liulilittle10 分钟前
C++实现广播地址计算
开发语言·c++
BingoGo13 分钟前
告别阻塞!用 PHP TrueAsync 实现 PHP 脚本提速 10 倍
后端·php
KD13 分钟前
阿里云服务器迁移实战(一)——Mysql平滑迁移
后端