ZetCode

Rust int 转 string

最后修改于 2025 年 2 月 19 日

在本文中,我们将展示如何在 Rust 中将整数转换为字符串。

整数到字符串的转换是一种类型转换,其中将整数数据类型的实体更改为字符串类型。

使用 to_string

to_string 函数将整数值转换为字符串。

main.rs
fn main() {

    let val = 4;
    let s1 = String::from("There are "); 
    let s2 = String::from(" hawks");
    
    let msg = s1 + &val.to_string() + &s2;

    println!("{}", msg)
}

在程序中,我们从两个字符串和一个整数构建一条消息。整数使用 to_string 转换为字符串。

λ rustc main.rs  
λ ./main.exe
There are 4 hawks

我们编译并运行程序。

使用 format!

我们可以使用 format! 宏进行转换。它使用运行时表达式的插值来创建 String

main.rs
fn main() {

    let val = 4;
    let msg = format!("There are {val} hawks");

    println!("{}", msg)
}

我们使用 format! 宏构建消息。

在本文中,我们在 Rust 中执行了 int 到 string 的转换。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。至今,我已撰写超过 1,400 篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 Rust 教程