我有一个 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
。
最佳答案
How do I get a
&str
使用
借用
:use std::borrow::Borrow; alphabet.push_str(example.borrow());
使用
AsRef
:alphabet.push_str(example.as_ref());
显式使用
Deref
:use std::ops::Deref; alphabet.push_str(example.deref());
通过强制转换隐式使用
Deref
:alphabet.push_str(&example);
How do I get a
String
使用
ToString
:example.to_string();
使用
Cow::into_owned
:example.into_owned();
使用任意方法获取引用然后调用
to_owned
:example.as_ref().to_owned();
关于string - 如何从 std::borrow::Cow<str> 获取 &str 或 String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47147844/