第1章 Hello World

Hello World — Rust By Example

译文 · 基于 Rust By Example

原文链接: https://doc.rust-lang.org/stable/rust-by-example/hello.html

Hello World

这是传统的 Hello World 程序的源码。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 这是注释内容,将会被编译器忽略掉
// 可以单击那边的按钮 "Run" 来测试这段代码 ->
// 若想用键盘操作,可以使用快捷键 "Ctrl + Enter" 来运行

// 这段代码支持编辑,你可以自由地修改代码!
// 通过单击 "Reset" 按钮可以使代码恢复到初始状态 ->

// 这是主函数
fn main() {
    // 调用编译生成的可执行文件时,这里的语句将被运行。

    // 将文本打印到控制台
    println!("Hello World!");
}

println! 是一个宏(macros),可以将文本输出到控制台(console)。

使用 Rust 的编译器 rustc 可以从源程序生成可执行文件:

1
$ rustc hello.rs

使用 rustc 编译后将得到可执行文件 hello。

1
2
$ ./hello
Hello World!

动手试一试

单击上面的 “Run” 按钮并观察输出结果。然后增加一行代码,再一次使用宏 println!,得到下面结果:

1
2
Hello World!
I'm a Rustacean!

01-注释

注释 — Rust By Example

02-格式化输出

格式化输出 — Rust By Example

最后修改 August 21, 2026: 更新 (76fc81a2e)