Rust笔记
变量的引用与克隆
本文档使用 MrDoc 发布
-
+
首页
变量的引用与克隆
# 变量的引用与克隆 ## 一个变量引用后不可以被修改 源码如下,s1 是一个mutable变量,但是在s2引用s1以后,如果修改s1,会panic ```rust fn main() { let mut s1 = String::from("abc"); let mut s2 = &s1; println!("{s2}"); s1.push_str("bcd"); println!("s2: {s2},s1: {s1}"); } ``` 执行输出: ```shell ➜ ownership git:(master) ✗ cargo run Compiling ownership v0.1.0 (/Users/icm/RustC/ownership) warning: variable does not need to be mutable --> src/main.rs:54:6 | 54 | let mut s2 = &s1; | ----^^ | | | help: remove this `mut` | = note: `#[warn(unused_mut)]` on by default error[E0502]: cannot borrow `s1` as mutable because it is also borrowed as immutable --> src/main.rs:56:2 | 54 | let mut s2 = &s1; | --- immutable borrow occurs here 55 | println!("{s2}"); 56 | s1.push_str("bcd"); | ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here 57 | println!("s2: {s2},s1: {s1}"); | ---- immutable borrow later used here For more information about this error, try `rustc --explain E0502`. warning: `ownership` (bin "ownership") generated 1 warning error: could not compile `ownership` (bin "ownership") due to previous error; 1 warning emitted ```
zhangky
2023年10月9日 23:15
分享文档
收藏文档
上一篇
下一篇
微信扫一扫
复制链接
手机扫一扫进行分享
复制链接
关于 MrDoc
觅思文档MrDoc
是
州的先生
开发并开源的在线文档系统,其适合作为个人和小型团队的云笔记、文档和知识库管理工具。
如果觅思文档给你或你的团队带来了帮助,欢迎对作者进行一些打赏捐助,这将有力支持作者持续投入精力更新和维护觅思文档,感谢你的捐助!
>>>捐助鸣谢列表
微信
支付宝
QQ
PayPal
Markdown文件
分享
链接
类型
密码
更新密码