问题描述
我有一个Cow
:
use std::borrow::Cow; // Cow = clone on write
let example = Cow::from("def")
我希望将def
从其中取出,以便将其追加到另一个String
:
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
// here I would like to do:
alphabet.push_str(example);
这不起作用,我在Cow
中找不到使&str
或String
退出的适当方法。
推荐答案
将对example
(即&example
)的引用传递给push_str
。
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
alphabet.push_str(&example);
这之所以有效,是因为Cow
实现了Deref
。