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"
相关推荐
背影疾风6 分钟前
C++之路:类基础、构造析构、拷贝构造函数
linux·开发语言·c++
Ting-yu10 分钟前
Java中Stream流的使用
java·开发语言·windows
【ql君】qlexcel39 分钟前
Notepad++ 复制宏、编辑宏的方法
开发语言·javascript·notepad++··宏编辑·宏复制
Zevalin爱灰灰1 小时前
MATLAB GUI界面设计 第六章——常用库中的其它组件
开发语言·ui·matlab
哔哩哔哩技术1 小时前
资源合池化后的异构差异问题解析--CPU分层现象和解决思路
后端
爱上语文1 小时前
Redis基础(4):Set类型和SortedSet类型
java·数据库·redis·后端
冰糖猕猴桃1 小时前
【Python】进阶 - 数据结构与算法
开发语言·数据结构·python·算法·时间复杂度、空间复杂度·树、二叉树·堆、图
wt_cs1 小时前
银行回单ocr api集成解析-图像文字识别-文字识别技术
开发语言·python
_WndProc2 小时前
【Python】Flask网页
开发语言·python·flask
深栈解码2 小时前
JMM深度解析(三) volatile实现机制详解
java·后端