我需要将一个 usize
转换为 &str
,以便传递给一个 fn foo(&str)
。我找到了以下两种方法,但不知道使用 as_str()
或者 Deref
之间是否有区别。也许 as_str
中的 self
所做的工作与 Deref
有所关联?我不知道使用其中的哪一个是更好的,或者它们实际上是否相同。
使用
temp.to_string().as_str()
:
使用#[inline] #[stable(feature = "string_as_str", since = "1.7.0")] pub fn as_str(&self) -> &str { self }
&*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) }
}
}
这个问题取决于您在 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)
}
to_string()
返回一个String
。对于&str
,我使用&*
。我认为在这种情况下我需要&*
,但是如果有更好的方式的话,那就不需要了吧? - Angel Angelfoo
是一个方法,那么temp.to_string().foo()
将自动解引用为&str
,但是foo
是一个函数,所以需要使用&*
。将usize
转换为String
是正确的方式。 - malbarbo