关于孤儿原则的详细介绍请参见特征定义与实现的位置孤儿规则 和 在外部类型上实现外部特征。
5. 🌟🌟
use std::fmt;
// 定 义 一 个 newtype Pretty
impl fmt::Display for Pretty {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, “”{}“”, self.0.clone() + “, world”)
}
}
fn main() {
let w = Pretty(“hello”.to_string());
println!(“w = {}”, w);
}
你可以在这里找到答案(在 solutions 路径下)
集合类型
学习资源:
简体中文: Rust语言圣经 - 集合类型
String
std::string::String 是 UTF-8 编码、可增长的动态字符串. 它也是我们日常开发中最常用的字符串类
型,同时对于它所拥有的内容拥有所有权。
基本操作
- 🌟🌟
// 填 空 并 修 复 错 误
// 1. 不 要 使 用to_string()
// 2. 不 要 添 加/删 除 任 何 代 码 行
fn main() {
let mut s: String = "hello, ";
s.push_str(“world”.to_string());
s.push(__);
move_ownership(s);
assert_eq!(s, “hello, world!”);
println!(“Success!”)
}
fn move_ownership(s: String) {
println!(“ownership of “{}” is moved here!”, s)
}
String and &str
虽然 String 的底层是 Vec 也就是字节数组的形式存储的,但是它是基于 UTF-8 编码的字符序列。
String 分配在堆上、可增长且不是以 null 结尾。
而 &str 是切片引用类型( &[u8] ),指向一个合法的 UTF-8 字符序列,总之, &str 和 String 的关系类
似于 &[T] 和 Vec 。
如果大家想了解更多,可以看看易混淆概念解析 - &str 和 String。 - 🌟🌟
// 填 空
fn main() {
let mut s = String::from(“hello, world”);
let slice1: &str = __; // 使 用 两 种 方 法
assert_eq!(slice1, “hello, world”);
let slice2 = __;
assert_eq!(slice2, “hello”);
let slice3: __ = __;
slice3.push(‘!’);
assert_eq!(slice3, “hello, world!”);
println!(“Success!”)
} - 🌟🌟
// 问 题: 我 们 的 代 码 中 发 生 了 多 少 次 堆 内 存 分 配 ?
// 你 的 回 答:
fn main() {
// 基 于&str
类 型 创 建 一 个 String,
// 字 符 串 字 面 量 的 类 型 是&str
let s: String = String::from(“hello, world!”);
// 创 建 一 个 切 片 引 用 指 向 Strings
let slice: &str = &s;
// 基 于 刚 创 建 的 切 片 来 创 建 一 个 String
let s: String = slice.to_string();
assert_eq!(s, “hello, world!”);
println!(“Success!”)
}