我无法编译将类型从整数转换为字符串的代码。我正在运行Rust for Rubyists教程中的示例,该示例具有各种类型转换,例如:
"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()
(此处运行示例):
let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);
你是对的; 为了保持一致性to_str()
,to_string()
在为了保持一致性而发布Rust 1.0之前,它被重命名为,因为现在分配了一个字符串String
。
如果您需要在某个地方传递字符串切片,则需要从获取&str
引用String
。这可以使用&
和反引力来完成:
let ss: &str = &s; // specifying type is necessary for deref coercion to fire
let ss = &s[..]; // alternatively, use slicing syntax
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句