Rust从入门到实战系列二百六十八:可变性

  1. 🌟 错误: 从不可变对象借用可变
    fn main() {
    // 通 过 修 改 下 面 一 行 代 码 来 修 复 错 误
    let s = String::from("hello, ");
    borrow_object(&mut s)
    }
    fn borrow_object(s: &mut String) {}
  2. 🌟🌟 Ok: 从可变对象借用不可变
    // 下 面 的 代 码 没 有 任 何 错 误
    fn main() {
    let mut s = String::from("hello, ");
    borrow_object(&s);
    s.push_str(“world”);
    }
    fn borrow_object(s: &String) {}
    NLL
  3. 🌟🌟
    // 注 释 掉 一 行 代 码 让 它 工 作
    fn main() {
    let mut s = String::from(“hello, “);
    let r1 = &mut s;
    r1.push_str(“world”);
    let r2 = &mut s;
    r2.push_str(”!”);
    println!(“{}”,r1);
    }
  4. 🌟🌟
    fn main() {
    let mut s = String::from("hello, ");
    let r1 = &mut s;
    let r2 = &mut s;
    // 在 下 面 增 加 一 行 代 码 人 为 制 造 编 译 错 误 :cannot borrow s as mutable more than once at
    // 你 不 能 同 时 使 用 r1 和 r2
    }
    复合类型
    学习资料:
    English: Rust Book 4.3, 5.1, 6.1, 8.2
    简体中文: Rust语言圣经 - 复合类型
    字符串
    字符串字面量的类型是 &str , 例如 let s: &str = “hello, world” 中的 “hello, world” 的类型就
    是 &str 。
    str 和 &str
  5. 🌟 正常情况下我们无法使用 str 类型,但是可以使用 &str 来替代
    // 修 复 错 误 , 不 要 新 增 代 码 行
    fn main() {
    let s: str = “hello, world”;
    }
  6. 🌟🌟 如果要使用 str 类型,只能配合 Box 。 & 可以用来将 Box 转换为 &str 类型
    // 使 用 至 少 两 种 方 法 来 修 复 错 误
    fn main() {
    let s: Box = “hello, world”.into();
    greetings(s)
    }
    fn greetings(s: &str) {
    println!(“{}”,s)
    }
    String
    String 是定义在标准库中的类型,分配在堆上,可以动态的增长。它的底层存储是动态字节数组的方式(
    Vec ),但是与字节数组不同, String 是 UTF-8 编码。
  7. 🌟
    // 填 空
    fn main() {
    let mut s = __;
    s.push_str(“hello, world”);
    s.push(‘!’);
    assert_eq!(s, “hello, world!”);
    }
  8. 🌟🌟🌟
    // 修 复 所 有 错 误 , 并 且 不 要 新 增 代 码 行
    fn main() {
    let s = String::from(“hello”);
    s.push(‘,’);
    s.push(" world");
    s += “!”.to_string();
    println!(“{}”, s)
    }
  9. 🌟🌟 我们可以用 replace 方法来替换指定的子字符串
    // 填 空
    fn main() {
    let s = String::from(“I like dogs”);
    // 以 下 方 法 会 重 新 分 配 一 块 内 存 空 间 , 然 后 将 修 改 后 的 字 符 串 存 在 这 里
    let s1 = s.__(“dogs”, “cats”);
    assert_eq!(s1, “I like cats”)
    }
    在标准库的 String 模块中,有更多的实用方法,感兴趣的同学可以看看。
  10. 🌟🌟 你只能将 String 跟 &str 类型进行拼接,并且 String 的所有权在此过程中会被 move
    // 修 复 所 有 错 误 , 不 要 删 除 任 何 一 行 代 码
    fn main() {
    let s1 = String::from(“hello,”);
    let s2 = String::from(“world!”);
    let s3 = s1 + s2;
    assert_eq!(s3,“hello,world!”);
    println!(“{}”,s1);
    }
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值