Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 我如何获得a&;str或std::borrow::Cow中的字符串<;str>;?_String_Rust_Concatenation - Fatal编程技术网

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
    的任何类似字符串的东西使用。这也非常有用。如果我能接受两个答案,我会:)