繁体   English   中英

如何从整数转换为字符串?

[英]How do I convert from an integer to a string?

我无法编译将类型从整数转换为字符串的代码。 我正在运行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()在 Rust 1.0 发布之前被重命名为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 Rust Programming Language的字符串章节

如果您希望向用户显示值(无论它是什么),请实现fmt::Display并使用to_string ,如另一个优秀答案中所述。

如果该值仍打算由计算机读取,但出于某种原因要作为字符串传递, 建议似乎是不要使用 Display 特征

这里有两个选项,使 Display 仅保留用于..良好的显示。

  • 实施 例子:
struct LargeNum(i128);

impl From<LargeNum> for String {
    fn from(LargeNum(amount): LargeNum) -> Self {
        amount.to_string()
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM