Rust简介
众所周知,在编程语言中,更易读的高级语言和控制底层资源的低级语言是一对矛盾体。Rust想要挑战这一现状,它尝试为开发者提供更好的体验的同时给予开发者控制底层细节的权限(比如内存使用)。
低级语言在开发过程中很容易出现各种细微的错误,它们难以发现但是可能影响巨大。其他大部分低级语言只能靠覆盖面更广的测试用例和经验丰富的开发者来解决这些问题。而Rust则依靠严格的编译器来杜绝这些问题。
Ps:以后会见识到Rust编译器的「厉害」
Rust的一些工具:
如果你的操作系统是Linux或macOS,在终端执行命令
1$ curl https://sh.rustup.rs -sSf | sh
安装过程中的选项使用默认就好(一路回车),直到出现以下信息时,表示安装成功。
1Rust is installed now. Great!
安装脚本会自动把Rust添加到环境变量PATH中,可以重启终端或者手动执行命令使添加生效。
1$ source $HOME/.cargo/env
当然也可以添加到你的.bash_profile文件中:
1$ export PATH="$HOME/.cargo/bin:$PATH"
最后,执行以下命令来检查Rust是否安装成功
1$ rustc --version
另外,当你尝试编译Rust代码,但报了linker不可执行的错误时,你需要手动安装一个linker,C编译器通常会包含正确的linker。Rust的一些公共包也会依赖C语言代码和编译器。所以最好现在安装一个。
IDEA中集成Rust也很简单,只需要在Preference->Plugins中搜索Rust,安装Rust插件后重启IDEA就可以了。
又到了经典的Hello World时间,这次我不想直接一个简单的print就结束了,我们一开始提到了Cargo是Rust依赖包的管理工具,所以我想体验一下Cargo的用法。
首先新建一个项目,可以直接用在IDEA中new project,也可以使用Cargo命令
1cargo new hello-world
2cd hello-world
新建好项目以后,它的结构长这样子
其中
接着我们在Cargo.toml文件中添加我们需要的依赖
1[dependencies]
2ferris-says = "0.1"
这时IDEA会自动安装依赖包,如果没有安装,也可以手动执行命令来安装
1cargo build
依赖安装好以后,就可以开始写代码了:
1use ferris_says::say;
2use std::io::{stdout, BufWriter};
3
4fn main() {
5 let stdout = stdout();
6 let out = b"Hello World!";
7 let width = 12;
8
9 let mut writer = BufWriter::new(stdout.lock());
10 say(out, width, &mut writer).unwrap();
11}
执行结果
1----------------
2| Hello World! |
3----------------
4 \
5 \
6 _~^~^~_
7 \) / o o \ (/
8 '_ - _'
9 / '-----' \
没错,这是一个小螃蟹,至于它是谁,来看看官方解释
Ferris is the unofficial mascot of the Rust Community. Many Rust programmers call themselves “Rustaceans,” a play on the word “crustacean.” We refer to Ferris with the pronouns “they,” “them,” etc., rather than with gendered pronouns. Ferris is a name playing off of the adjective, “ferrous,” meaning of or pertaining to iron. Since Rust often forms on iron, it seemed like a fun origin for our mascot’s name! You can find more images of Ferris on http://rustacean.net/.