且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从整数转换为字符串?

更新时间:2023-01-16 17:53:25

使用 to_string() (在这里运行示例):

let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);

你是对的;to_str() 在 Rust 1.0 发布之前已重命名为 to_string() 以保持一致性,因为分配的字符串现在称为 String.


You're right; to_str() was renamed to to_string() before Rust 1.0 was released for consistency because an allocated string is now called String.

如果你需要在某处传递一个字符串切片,你需要从 String 获取一个 &str 引用.这可以使用 & 和 deref coercion 来完成:

If you need to pass a string slice somewhere, you need to obtain a &str reference from String. This can be done using & and a deref coercion:

let ss: &str = &s;   // specifying type is necessary for deref coercion to fire
let ss = &s[..];     // alternatively, use slicing syntax

您链接到的教程似乎已过时.如果您对 Rust 中的字符串感兴趣,可以查看 字符串章节Rust 编程语言.

The tutorial you linked to seems to be obsolete. If you're interested in strings in Rust, you can look through the strings chapter of The Rust Programming Language.