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

时间:2016-04-27 20:29:03

标签: rust

我需要将usize转换为&str以传递给fn foo(&str)。我发现了以下两种方法,但不知道使用as_str()Deref之间是否存在差异。也许selfas_strDeref以某种方式联系完成的工作?我不知道使用其中一个或者它们实际上是否相同可能更好。

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

    #[inline]
    #[stable(feature = "string_as_str", since = "1.7.0")]
    pub fn as_str(&self) -> &str {
        self
    }
    
  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) }
        }
    }
    
  3.   

    问题可能取决于你在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)
    }
    

    termbox_sys

1 个答案:

答案 0 :(得分:1)

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

相关问题