string 如何将整数转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24990520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert from an integer to a string?
提问by user3358302
I am unable to compile code that converts a type from an integer to a string. I'm running an example from the Rust for Rubyists tutorialwhich has various type conversions such as:
我无法编译将类型从整数转换为字符串的代码。我正在运行Rust for Rubyists 教程中的一个示例,该示例具有各种类型转换,例如:
"Fizz".to_str()
and num.to_str()
(where num
is an integer).
"Fizz".to_str()
和 num.to_str()
(其中num
是一个整数)。
I think the majority (if not all) of these to_str()
function calls have been deprecated. What is the current way to convert an integer to a string?
我认为大多数(如果不是全部)这些to_str()
函数调用已被弃用。当前将整数转换为字符串的方法是什么?
The errors I'm getting are:
我得到的错误是:
error: type `&'static str` does not implement any method in scope named `to_str`
error: type `int` does not implement any method in scope named `to_str`
回答by Vladimir Matveev
Use to_string()
(running example here):
使用to_string()
(在此处运行示例):
let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);
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
.
你是对的; 在 Rust 1.0 发布之前to_str()
被重命名to_string()
为一致性,因为分配的字符串现在被称为String
.
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:
如果需要在某处传递字符串切片,则需要&str
从String
. 这可以使用&
和 deref 强制来完成:
let ss: &str = &s; // specifying type is necessary for deref coercion to fire
let ss = &s[..]; // alternatively, use slicing syntax
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.
您链接到的教程似乎已过时。如果您对 Rust 中的字符串感兴趣,可以查看The Rust Programming Language的字符串章节。