【问题标题】:How do I convert from an integer to a string?如何从整数转换为字符串?
【发布时间】:2014-09-19 08:41:00
【问题描述】:

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

【问题讨论】:

  • 对不起,如果我不关注,但我已经尝试查找 int 源,它似乎使用 doc.rust-lang.org/0.11.0/std/num/strconv/index.html 但这只是返回一个字节向量。此外还有 to_string() 方法,但它返回 String 而不是文字字符串。
  • 哈哈没关系,我以为to_str()是一个不同的返回值,我会用to_string()
  • @user3358302,没有方法可以返回你称之为“文字字符串”的东西,除非它们确实返回静态已知的文字,因为这些值的类型为&'static str,即具有静态生命周期的字符串切片,这是使用动态创建的数据无法获得的。您只能使用字符串文字来创建它们。
  • 很高兴知道!我认为 to_str 方法让我感到困惑(正如您所说,为了清楚起见,他们重命名)认为它返回的是字符串切片而不是 String 对象。

标签: string int type-conversion rust


【解决方案1】:

使用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 发生变化。
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 2010-10-13
  • 1970-01-01
相关资源
最近更新 更多