惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
N
Netflix TechBlog - Medium
博客园_首页
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Y
Y Combinator Blog
腾讯CDC
V
V2EX
Microsoft Security Blog
Microsoft Security Blog
大猫的无限游戏
大猫的无限游戏
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
Schneier on Security
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News: Ask HN
Hacker News: Ask HN
Martin Fowler
Martin Fowler
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
U
Unit 42
WordPress大学
WordPress大学
N
News and Events Feed by Topic
S
Schneier on Security
T
The Blog of Author Tim Ferriss
B
Blog
博客园 - 叶小钗
Forbes - Security
Forbes - Security
F
Fortinet All Blogs
Project Zero
Project Zero
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
L
LINUX DO - 热门话题
The GitHub Blog
The GitHub Blog
H
Hacker News: Front Page
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
PCI Perspectives
PCI Perspectives
The Register - Security
The Register - Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
W
WeLiveSecurity
C
Cyber Attacks, Cyber Crime and Cyber Security
罗磊的独立博客
S
Security @ Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
P
Proofpoint News Feed
S
SegmentFault 最新的问题
D
Docker
量子位
M
MIT News - Artificial intelligence

博客园 - PKICA

编译配置解答 git实用命令 rust底层设计理念值得注意的几个地方总结 rust可变引用作为函数参数的机理详解 Rust内存重解释transmute C与Rust类型映射 Rust FFI 安全抽象范式 rust延迟初始化原语 rust重借用机制与原理 rust参数传递模型 汇编语言语法详解 gdb汇编调试 gdb-pwndbg的安装与使用指南 gdb调试插件gef C语言thread_local linux系统readelf命令使用指南 gcore转储进程内存 gdb查看命令 RGB与YUV颜色编码的区别 Rust原子类型 C++ STL求两个集合交集差集 gdb调试集锦 ubuntu24.0.4使用root用户登录 ubuntu24.0.4输入密码后跳回登录界面 AI内存压缩技术TurboQuant及存疑 ubuntu切换到指定内核版本 在没有顶级科技大佬直接背书的情况下deepseek为啥能够异军突起? HuggingFace和deepseek的关系 当前主流AI大模型
Rust写时克隆Cow系列2
PKICA · 2026-02-28 · via 博客园 - PKICA

细心的同学也许会发现,讲了Cow,那么Cow能够接受任意类型参数吗?咱先说答案,不可以。至于为什么呢?请同学们接着往下读。

在 Rust 中,Cow<'a, B>::Owned 变体接受的类型由泛型参数 B 决定,其约束规则非常明确:

1. 核心约束:ToOwned 关联类型

Cow::Owned 接受的数据类型必须是 B 类型关联的“拥有所有权”版本
具体语法定义如下:

pub enum Cow<'a, B> where B: 'a + ToOwned + ?Sized {
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned), // 接受的就是这个类型
}

2. 常见匹配关系表

在实际开发中,最常与 Cow 搭配的类型如下:

借用类型 B (Borrowed)
Cow::Owned 接受的类型示例场景
str String 处理字符串,如 Cow<'static, str>
[T] (切片) Vec<T> 处理列表数据
Path PathBuf 处理文件路径
CStr CString 处理 FFI 中的 C 字符串
T (已实现 Clone) T 任何实现 Clone 的普通结构体

3. 为什么不直接接受任意类型?

Cow(Copy-on-Write)的设计初衷是在需要修改数据时能从借用态转换为拥有态

  • 如果你传入一个自定义类型 MyStruct 给 Cow::Owned,编译器要求必须存在一个对应的 B 类型,使得 B::to_owned() 能产生该 MyStruct
  • 通常对于普通的 Clone 类型,B 和 Owned 是同一种类型。 

4. 变体即函数语法回顾

正如之前提到的,Cow::Owned 本身也是一个构造函数。

let s = String::from("Hello");
// Cow::Owned 作为一个 fn(String) -> Cow<str> 的函数指针
let my_cow: Cow<str> = Cow::Owned(s); 

参考资料:

1.Rust写时克隆Cow

2.Rust枚举变体详解

3.rust语言泛型实现