string - 如何从 std::borrow::Cow<str> 获取 &str 或 String?

标签 string rust concatenation

我有一个 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 中没有看到适当的方法来获取 &strString

最佳答案

How do I get a &str

  1. 使用借用:

    use std::borrow::Borrow;
    alphabet.push_str(example.borrow());
    
  2. 使用AsRef:

    alphabet.push_str(example.as_ref());
    
  3. 显式使用Deref:

    use std::ops::Deref;
    alphabet.push_str(example.deref());
    
  4. 通过强制转换隐式使用 Deref:

    alphabet.push_str(&example);
    

How do I get a String

  1. 使用ToString:

    example.to_string();
    
  2. 使用Cow::into_owned:

    example.into_owned();
    
  3. 使用任意方法获取引用然后调用to_owned:

    example.as_ref().to_owned();
    

关于string - 如何从 std::borrow::Cow<str> 获取 &str 或 String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47147844/

相关文章:

mysql - MYSQL中存在空值时如何进行GROUP_CONCAT?

C - `0` 使用 malloc 出现特殊字符

python - 如何在 python pandas 中使用两个列值创建 url 列数据框?

rust - 匹配错误结果并在分配变量时退出程序

r - 在长度超过 n 个字符的单词之间包含空格

C# SQL 搜索结果到字符串/文本框

c# - 在 C# 中编辑字符串中的字符

multithreading - 如何从标准库生成的线程向 Tokio 异步任务发送消息?

for-loop - 元组在for循环中被破坏了吗?

php - 如何在 PHP 中存储字符串中的变量