天天看点

3.Rust的“Hello World”

在部署好Rust的编译程序之后,就可以编写Rust的第一个程序了。按照惯例,都是“Hello World”。

在Rust的官方书的1.2节就是“Hello World”。在这个章节中,首先创建了一个目录来容纳程序的源文件以及程序本身,文中也说了,这不是必需的,但是一个良好的习惯,然后就是创建一个名为main.rs的文件,并在其中输入如下的代码:

fn main() {
    println!("Hello, world!");
}      

保存后,在命令行中使用rustc对它进行编译:

rustc main.rs      

不出意外的话就会得到一个main.exe程序(Windows平台)以及main.pdb,执行main.exe就可以看到如下的结果:

Hello, world!      

由于是新接触Rust,对什么都好奇,光是这一个小小的“Hello World”就能找到很多种探索的方式。下面我就来分享一下我的探索旅程。

1.修改文件名,看看文件名,看看是不是和Java那样,文件名对文件内容也产生了影响。​​先把文件名改成first.rs​​,然后再编译。

结果是,编译得到的exe、pdb文件的文件名变了,变成了first,也就是说,在rustc默认的编译条件下,它会把源文件的文件名直接带入到可执行文件上。

问题:如果有多个文件组成的工程,那么编译之后,默认的可执行文件会是哪个名字?

2.修改源文件的后缀名,文档中提到Rust的源文件后缀名都是rs,那么如果改掉,编译器就不认是了吗?

首先随便把后缀名改成别的,如rs0。然后使用编译器编译。

结果发现,它依然能编译成可执行文件,看来这个rs的后缀名是个约定俗成,并不具有强制力。

下面开始,对文件内容进行编辑了。

3.首先,把fn这个去掉,看看会弹出什么提示。

error: expected one of `!` or `::`, found `(`
 --> F:\Code Space\hello_world\main.rs:1:5
  |
1 | main() {
  |     ^ expected one of `!` or `::`

error: aborting due to previous error      

这提示,说实话,还真的不容易认,并没有直接告诉你main缺少了fn类型声明,估计在Rust中,这种写法是有意义的。

4.把main换成别的名称看看。

error[E0601]: `main` function not found in crate `main`
 --> F:\Code Space\hello_world\main.rs:3:2
  |
3 | }
  |  ^ consider adding a `main` function to `F:\Code Space\hello_world\main.rs`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0601`.      

这个错误提示比较明确,直接说明了没找到main函数,还建议我们添加一个main函数到文件里。

5.把main函数的参数元组去掉。

error: expected one of `(` or `<`, found `{`
 --> F:\Code Space\hello_world\main.rs:1:9
  |
1 | fn main {
  |         ^ expected one of `(` or `<`

error: aborting due to previous error      

这个错误提示指向也不是特别明确,但是一般这种缺参数元组的错误很少有码农会犯的。

6.把main函数的大括号去掉。

error: expected one of `->`, `where`, or `{`, found `println`
 --> F:\Code Space\hello_world\main.rs:2:2
  |
1 | fn main() 
  |          - expected one of `->`, `where`, or `{`
2 |     println!("Hello, world!");
  |     ^^^^^^^ unexpected token

error: aborting due to previous error      

这个错误提示还算比较明显,不过,就和上一个错误一样,不太有可能有人犯这样的错误,毕竟任何IDE中,都会有比较明显的提示。

7.把main的大括号{放在独立的一行。这个举动不会构成错误,看来Rust和大多数语言一样,不像Go那种,连括号放哪都要有规定。毕竟,这种括号放哪仅仅表示一种习惯,遵循团队内一致就行了。

8.去掉函数内的缩进。这个举动也不影响,不会像Python那样视为语法错误。不过良好的缩进级别是非常必须的,对理清代码关系相当有帮助,还是应该坚持。

9.把println!的!去掉。

error[E0423]: expected function, found macro `println`
 --> F:\Code Space\hello_world\main.rs:2:2
  |
2 |     println("Hello, world!");
  |     ^^^^^^^ not a function
  |
help: use `!` to invoke the macro
  |
2 |     println!("Hello, world!");
  |            +

error: aborting due to previous error

For more information about this error, try `rustc --explain E0423`.      

这个错误提示还是比较明显的,告诉我们println不是一个函数。我记得按照Rust的说法,println是一个宏,一定要使用!来与函数区分。

问题:Rust的宏与C/C++里的宏有没有什么相似处。

10.把"Hello, world!"的引号去掉。

error: expected one of `(`, `[`, or `{`, found `<eof>`
 --> F:\Code Space\hello_world\main.rs:2:23
  |
2 |     println!(Hello, world!);
  |                          ^ expected one of `(`, `[`, or `{`

error: aborting due to previous error