String 我如何获得a&;str或std::borrow::Cow中的字符串<;str>;?
我有一个: 我想将String 我如何获得a&;str或std::borrow::Cow中的字符串<;str>;?,string,rust,concatenation,String,Rust,Concatenation,我有一个: 我想将def从中取出,以便将其附加到另一个字符串中: let mut alphabet: String = "ab".to_string(); alphabet.push_str("c"); // here I would like to do: alphabet.push_str(example); example.to_string(); 这不起作用,我在Cow中看不到将&str或字符串返回的适当方法。将对示例(即示例)的引用传递到推送str let mut alphabet
def
从中取出,以便将其附加到另一个字符串中:
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
// here I would like to do:
alphabet.push_str(example);
example.to_string();
这不起作用,我在Cow
中看不到将&str
或字符串
返回的适当方法。将对示例
(即示例
)的引用传递到推送str
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
alphabet.push_str(&example);
这是因为Cow
实现了
如何获得&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);
如何获取字符串
使用ToString
:
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
// here I would like to do:
alphabet.push_str(example);
example.to_string();
使用Cow::进入您拥有的
:
example.into_owned();
example.as_ref().to_owned();
使用任何方法获取引用,然后调用至_owned
:
example.into_owned();
example.as_ref().to_owned();
啊,这就是它的工作原理!我需要记住这一点,以备将来实现Deref
的任何类似字符串的东西使用。这也非常有用。如果我能接受两个答案,我会:)