将 `usize` 转换为 `&str` 的最佳方法是什么?

Ang*_*gel 7 rust

我需要将 a 转换usize为 a&str以传递给 a fn foo(&str)。我找到了以下两种方式,但不知道使用as_str()或有没有区别Deref。也许以某种方式selfas_str链接中完成的工作Deref?我不知道使用一种或另一种是否更好,或者它们实际上是否相同。

  1. 使用temp.to_string().as_str()

    #[inline]
    #[stable(feature = "string_as_str", since = "1.7.0")]
    pub fn as_str(&self) -> &str {
        self
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用&*temp.to_string()&temp.to_string()。这通过Deref

    #[stable(feature = "rust1", since = "1.0.0")]
    impl ops::Deref for String {
        type Target = str;
    
        #[inline]
        fn deref(&self) -> &str {
            unsafe { str::from_utf8_unchecked(&self.vec) }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

问题可能取决于您想在 foo 中做什么:传递的 &str是否需要生存foo

foo(&str)s: &str此代码中的最小示例:

extern crate termbox_sys as termbox;

pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) {
    let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
    let bg = Style::from_color(bg);
    for (i, ch) in s.chars().enumerate() {
        unsafe {
            self.change_cell(x + i, y, ch as u32, fg.bits(), bg.bits());
        }
    }
}

pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) {
    termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg)
}
Run Code Online (Sandbox Code Playgroud)

termbox_sys

dur*_*a42 2

正如您所注意到的,它as_str似乎没有做任何事情。事实上,它返回self, a &String,其中&str应为 a 。这会导致编译器插入对Deref. 所以你的两种方式是完全一样的。