我无法编译将类型从整数转换为字符串的代码.我正在运行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.

如果需要在某个地方传递字符串片段,则需要从String获取&str引用.这可以通过使用&和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页.

Rust相关问答推荐

收集RangeInclusive T到Vec T<><>

如何从铁 rust 中呼唤_mm_256_mul_ph?

为什么允许我们将可变引用转换为不可变引用?

原始数组数据类型的默认trait实现

当发送方分配给静态时,Tokio MPSC关闭通道

在 Rust 中,在需要引用 self 的 struct 体方法中使用闭包作为 while 循环条件

使用 select 处理 SIGINT 和子等待!无阻塞

实现 Deref 的 struct 可以返回对外部数据的引用吗?

如何处理闭包中的生命周期以及作为参数和返回类型的闭包?

Sized问题的动态调度迭代器Rust

由特征键控的不同 struct 的集合

打印 `format_args!` 时borrow 时临时值丢失

如何将 Rust 字符串转换为 i8(c_char) 数组?

使用 rust 在 google cloud run (docker) 中访问环境变量的适当方法

&str 的编译时拆分是否可能?

Rust 中的let是做什么的?

通用函数中的生命周期扣除和borrow (通用测试需要)

以下打印数组每个元素的 Rust 代码有什么问题?

当特征函数依赖于为 Self 实现的通用标记特征时实现通用包装器

如何将 while 循环内的用户输入添加到 Rust 中的向量?