如何从整数转换为字符串? [英] How do I convert from an integer to a string?

查看:18
本文介绍了如何从整数转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法编译将类型从整数转换为字符串的代码.我正在运行 Rust for Rubyists 教程 中的一个示例,该示例具有各种类型转换,例如:

I am unable to compile code that converts a type from an integer to a string. I'm running an example from the Rust for Rubyists tutorial which has various type conversions such as:

"Fizz".to_str()num.to_str()(其中 num 是一个整数).

"Fizz".to_str() and num.to_str() (where num is an integer).

我认为这些 to_str() 函数调用中的大多数(如果不是全部)已被弃用.当前将整数转换为字符串的方法是什么?

I think the majority (if not all) of these to_str() function calls have been deprecated. What is the current way to convert an integer to a string?

我得到的错误是:

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.


You're right; to_str() was renamed to to_string() before Rust 1.0 was released for consistency because an allocated string is now called String.

如果你需要在某处传递一个字符串切片,你需要从 String 获取一个 &str 引用.这可以使用 & 和 deref coercion 来完成:

If you need to pass a string slice somewhere, you need to obtain a &str reference from String. This can be done using & and a deref coercion:

let ss: &str = &s;   // specifying type is necessary for deref coercion to fire
let ss = &s[..];     // alternatively, use slicing syntax

您链接到的教程似乎已过时.如果您对 Rust 中的字符串感兴趣,可以查看 字符串章节Rust 编程语言.

The tutorial you linked to seems to be obsolete. If you're interested in strings in Rust, you can look through the strings chapter of The Rust Programming Language.

这篇关于如何从整数转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆