Rust从入门到实战系列二百九十四:孤儿原则

关于孤儿原则的详细介绍请参见特征定义与实现的位置孤儿规则 和 在外部类型上实现外部特征。
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. 🌟🌟
    // 填 空 并 修 复 错 误
    // 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。
  2. 🌟🌟
    // 填 空
    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!”)
    }
  3. 🌟🌟
    // 问 题: 我 们 的 代 码 中 发 生 了 多 少 次 堆 内 存 分 配 ?
    // 你 的 回 答:
    fn main() {
    // 基 于 &str 类 型 创 建 一 个 String,
    // 字 符 串 字 面 量 的 类 型 是 &str
    let s: String = String::from(“hello, world!”);
    // 创 建 一 个 切 片 引 用 指 向 String s
    let slice: &str = &s;
    // 基 于 刚 创 建 的 切 片 来 创 建 一 个 String
    let s: String = slice.to_string();
    assert_eq!(s, “hello, world!”);
    println!(“Success!”)
    }
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值