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

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

问题描述

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

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

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

我得到的错误是:

 错误:类型`&'static str`在名为`to_str`的​​作用域中未实现任何方法错误:类型"int"在名为"to_str"的范围内未实现任何方法 

解决方案

使用 to_string() (在此处运行示例):

  let x:u32 = 10;让s:字符串= x.to_string();println!("{}",s); 


您是对的;为了保持一致性,在Rust 1.0发布之前, to_str()被重命名为 to_string(),因为分配的字符串现在称为字符串一章 Rust编程语言 的说明.

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() and num.to_str() (where num is an integer).

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?

The errors I'm getting are:

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`

解决方案

Use to_string() (running example here):

let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);


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.

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

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天全站免登陆