Skip to main content

基础

安装

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

苹果电脑可以

brew install rust

查看安装的版本

rustc --version

更新

rustup update

Cargo

构建工具和包管理器

cargo build # 构建
cargo run # 运行
cargo test # 测试
cargo doc # 构建文档
cargo publish # 发布包
cargo --version # 查看版本

构建和查看本地依赖的文档

cargo doc --open

创建新项目

cargo new hello-rust

文件结构

hello-rust
|- Cargo.toml
|- src
|- main.rs

Cargo.toml 配置文件

src/main.rs 代码入口文件

创建好后,可以到项目目录下执行下面命令运行项目。

cargo run

添加依赖

Cargo.toml 文件中添加

[dependencies]
ferris-says = "0.2"

执行 cargo build 安装依赖。

使用依赖,使用 ferris-says 包中的 say 方法

use ferris_says::say;

不要混淆 nodejs 和浏览器中的 event loop

stop-using-default-exports-javascript-module

按模块进行分层,

对 web 请求,业务逻辑,数据存取操作分层

使用原生错误对象,而不是字符串

区分运行时错误和编码错误

集中进行错误处理,但不要在中间件中处理

参考