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

46

我有一个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的适当方法。

2个回答

89

如何获取&str

  1. 使用Borrow

    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);
    

如何获取一个字符串(String

  1. 使用 ToString 方法:

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

    example.into_owned();
    
  • 使用任何方法获取引用,然后调用to_owned

  • example.as_ref().to_owned();
    

    非常有帮助。如果我可以接受两个答案,我会的:) - Zelphir Kaltstahl
    2
    未来的读者请注意:在“How do I get a String”中,into_owned会消耗Cow并仅在Cow::Borrowed的情况下分配内存,而to_stringas_ref + to_owned则保持Cow不变并无条件地分配内存。它们对于Cow::Borrowed是等效的,但对于Cow::Owned类似于移动和克隆的区别。 - L. F.

    18

    将对 example 的引用(即&example)传递给 push_str

    let mut alphabet: String = "ab".to_string();
    alphabet.push_str("c");  
    alphabet.push_str(&example);
    

    这能够工作是因为Cow实现了Deref


    1
    啊,原来是这样!我需要记住这个,以备将来有任何像字符串一样实现 Deref 的东西。 - Zelphir Kaltstahl

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接