string - 如何将整数转换为字符串?

标签 string int type-conversion rust

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

相关文章:

c# - C# 中的字符串操作以递增数字

c - 为什么指针 "Start"会改变? (C)

python - 为什么我的新分割数组元素被视为非 int 值?

java - 如何将 Map<Object, List<Object>> 传递给 Struts 2 中的操作

c++ - C++的一些转换题

java - 如何防止用户使用 JOptionpane 输入字符、字符串和空格

javascript - ie6和ie7中简单的javascript字符串问题

php - 如何在 PHP 中将 11、22、33 转换为 10、20 和 30?

objective-c - Objective C - 数字数组

c++ - unsigned int 和 double 转换顺序