簡體   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