use*_*302 56 string int type-conversion rust
我无法编译将类型从整数转换为字符串的代码.我正在运行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`
Run Code Online (Sandbox Code Playgroud)
Vla*_*eev 89
只需使用to_string()(此处运行示例):
let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);
Run Code Online (Sandbox Code Playgroud)
你是对的,在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
Run Code Online (Sandbox Code Playgroud)
您链接的教程似乎已过时.如果您对Rust中的字符串感兴趣,可以查看The Rust Programming Language的字符串章节.
| 归档时间: |
|
| 查看次数: |
51268 次 |
| 最近记录: |