Zel*_*ahl 7 string concatenation rust
我有一个Cow:
use std::borrow::Cow; // Cow = clone on write
let example = Cow::from("def")
Run Code Online (Sandbox Code Playgroud)
我想def退出它,以便将它追加到另一个String:
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
// here I would like to do:
alphabet.push_str(example);
Run Code Online (Sandbox Code Playgroud)
这不起作用,我没有看到适当的方法Cow来获取&str或String退出.
She*_*ter 12
我怎么得到一个
&str
用途Borrow:
use std::borrow::Borrow;
alphabet.push_str(example.borrow());
Run Code Online (Sandbox Code Playgroud)用途AsRef:
alphabet.push_str(example.as_ref());
Run Code Online (Sandbox Code Playgroud)Deref明确使用:
use std::ops::Deref;
alphabet.push_str(example.deref());
Run Code Online (Sandbox Code Playgroud)Deref通过胁迫隐式使用:
alphabet.push_str(&example);
Run Code Online (Sandbox Code Playgroud)我怎么得到一个
String
用途ToString:
example.to_string();
Run Code Online (Sandbox Code Playgroud)用途Cow::into_owned:
example.into_owned();
Run Code Online (Sandbox Code Playgroud)使用任何方法获取引用,然后调用to_owned:
example.as_ref().to_owned();
Run Code Online (Sandbox Code Playgroud)传递到一个参考example(即&example),以push_str。
let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
alphabet.push_str(&example);
Run Code Online (Sandbox Code Playgroud)
这是因为Cow实现了Deref。