- 🌟 错误: 从不可变对象借用可变
fn main() {
// 通 过 修 改 下 面 一 行 代 码 来 修 复 错 误
let s = String::from("hello, ");
borrow_object(&mut s)
}
fn borrow_object(s: &mut String) {} - 🌟🌟 Ok: 从可变对象借用不可变
// 下 面 的 代 码 没 有 任 何 错 误
fn main() {
let mut s = String::from("hello, ");
borrow_object(&s);
s.push_str(“world”);
}
fn borrow_object(s: &String) {}
NLL - 🌟🌟
// 注 释 掉 一 行 代 码 让 它 工 作
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);
} - 🌟🌟
fn main() {
let mut s = String::from("hello, ");
let r1 = &mut s;
let r2 = &mut s;
// 在 下 面 增 加 一 行 代 码 人 为 制 造 编 译 错 误 :cannot borrows
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 - 🌟 正常情况下我们无法使用 str 类型,但是可以使用 &str 来替代
// 修 复 错 误 , 不 要 新 增 代 码 行
fn main() {
let s: str = “hello, world”;
} - 🌟🌟 如果要使用 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 编码。 - 🌟
// 填 空
fn main() {
let mut s = __;
s.push_str(“hello, world”);
s.push(‘!’);
assert_eq!(s, “hello, world!”);
} - 🌟🌟🌟
// 修 复 所 有 错 误 , 并 且 不 要 新 增 代 码 行
fn main() {
let s = String::from(“hello”);
s.push(‘,’);
s.push(" world");
s += “!”.to_string();
println!(“{}”, s)
} - 🌟🌟 我们可以用 replace 方法来替换指定的子字符串
// 填 空
fn main() {
let s = String::from(“I like dogs”);
// 以 下 方 法 会 重 新 分 配 一 块 内 存 空 间 , 然 后 将 修 改 后 的 字 符 串 存 在 这 里
let s1 = s.__(“dogs”, “cats”);
assert_eq!(s1, “I like cats”)
}
在标准库的 String 模块中,有更多的实用方法,感兴趣的同学可以看看。 - 🌟🌟 你只能将 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);
}
Rust从入门到实战系列二百六十八:可变性
最新推荐文章于 2024-08-04 12:24:40 发布