我无法编译将类型从整数转换为字符串的代码。我正在从Rust for Rubyists tutorial运行一个示例,该示例具有各种类型转换,例如:"Fizz".to_str()
和num.to_str()
(其中num
是整数)。
我认为大多数to_str()
函数调用(如果不是全部)都已弃用。当前将整数转换为字符串的方法是什么?
我得到的错误是:
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`
最佳答案
使用 to_string()
(running example here):
let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);
你是对的;为了保持一致性,在Rust 1.0发布之前,
to_str()
重命名为to_string()
,因为现在分配的字符串称为 String
。如果需要在某个地方传递字符串切片,则需要从
&str
获得String
引用。这可以使用&
和deref强制执行:let ss: &str = &s; // specifying type is necessary for deref coercion to fire
let ss = &s[..]; // alternatively, use slicing syntax
您链接到的教程似乎已过时。如果您对Rust中的字符串感兴趣,可以浏览the strings chapter of The Rust Programming Language。
关于string - 如何将整数转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65584770/