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

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - PKICA

汇编语言语法详解 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 搭配的类型如下:

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

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语言泛型实现