Rust中的智能指针 Cow
全称:std::borrow::Cow<'a, B>
理解: 名称 Cow 参数 'a 为生命周期参数 B 为基础参数
Rust规定 枚举 都必须至少有一个变体
Cow 拥有两个变体
Borrowed(&'a B):表示对数据的不可变借用。
Owned(<B as ToOwned>::Owned):表示拥有数据的克隆副本。
用法:处理可能来自借用或拥有的数据,避免非必要克隆。
- Cow 实现了
Deref
- 需要可变性时,Cow会自动克隆(写时)
用例:
- 避免不必要的字符串克隆:例如,处理输入可能是
&str 或 String 的情况。
- 优化函数返回类型:函数可能返回借用或拥有的数据,取决于条件。
- 处理配置或默认值:避免复制默认值,除非需要修改。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| use std::borrow::Cow;
fn process_input(input: &str) -> Cow<str> { if input.contains("special") { Cow::Owned(input.to_uppercase()) } else { Cow::Borrowed(input) } }
fn get_config_value(setting: Option<String>) -> Cow<str> { match setting { Some(s) => Cow::Owned(s), None => Cow::Borrowed("default_value"), } }
fn main() { let input1 = "hello world"; let result1 = process_input(input1); println!("Result1: {}", result1);
let input2 = "special input"; let result2 = process_input(input2); println!("Result2: {}", result2);
let config1 = get_config_value(Some("custom".to_string())); let config2 = get_config_value(None); println!("Config1: {}, Config2: {}", config1, config2); }
|