你好,我是鹿洺。从本文开始,我将和你一起学习rust。在开始之前,你需要完成rust工具链的安装。
工欲善其事必先利其器,你可以使用任何编辑器来写rust代码,我比较喜欢VSCode,它免费,功强大而且速度很快。在VSCode下我安装了一些插件来提供效率,你有兴趣也可以参考:
- rust-analyzer:会实时编译和分析你的rust代码,提示代码中的错误,并对类型进行标注
- rust syntax:为你的rust代码提供语法高亮
- crates:帮助你分析当前项目的依赖是否是最新的版本
- better toml:rust使用toml做项目的配置管理,它可以帮你语法高亮,并展示toml文件中的错误
- rust test lens:可以帮助你快速运行某个rust测试
- tabnine:基于AI的自动补全,可以帮助你更快撰写代码
现在,按照传统,我们动手来写第一个rust程序。我们在本地命令行使用cargo new来创建项目。
> cargo new hello
Created binary (application) `hello` package
此时,会自动帮我们创建一个可执行的项目hello,入口在src/main.rs,项目配置在Cargo.toml文件里,println!是rust里的宏函数,可以简化我们的代码。
// 项目入口
fn main() {
println!("Hello, world!");
}
[package]
name = "hello"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
进入这个项目目录,我们运行cargo run,经过编辑后,程序开始运行。
> cd .\hello\
> cargo run
Compiling hello v0.1.0 (F:\projects\start-rust\hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.67s
Running `target\debug\hello.exe`
Hello, world!
我们的第一个rust程序运行成功!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。