これは何?
いまさら,Rustに入門したのでやった環境構築とかメモしておきます。
install
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain 1.80.0
apt-get install -y --no-install-recommends gcc=4cargo --version:12.2.0-3 libc6-dev=2.36-9+deb12u8
source "$HOME/.cargo/env"
tools
rustup
- rustのインストールやバージョン管理を行うことができるツール
- 公式サイト
- rustcやcargoなども一括でインストールされる。
rustc
rustのコンパイラ
cargo
- rustのビルドシステム兼パッケージマネージャ
-
Cargo.toml
でプロジェクト管理する。
[!NOTE]
Rustではパッケージのことをクレート(Crate)と呼ぶ。
cargo new プロジェクト名
cargo clean
cargo check # コンパイルできるかチェックする
cargo build
cargo run
リリースに向けたビルド
--release
をつけると最適化が行われ、コンパイル時間が長くなる代わりに実行速度が速くなる。
cargo build # target/debugに
cargo build --release # target/releaseに
パッケージの追加
-
Cargo.toml
の[dependencies]
に追加する。
[package]
name = "chapter2"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.3" # ここに追加
-
cargo build
でライブラリが追加される。
[!NOTE]
Cargo.lock
には依存関係のバージョンが記録される。
-
cargo update
を使うとCargo.lock
を無視してCargo.toml
のバージョンを元に更新が走る。
コンパイラのエラーを直す
コードをコミットをせずに実行すると以下のようなエラーがでる。
cargo fix
error: the working directory of this package has uncommitted changes, and `cargo fix` can potentially perform destructive changes; if you'd like to suppress this error pass `--allow-dirty`, `--allow-staged`, or commit the changes to these files:
...
コードを修正してコミットするか、--allow-dirty
をつけて実行するか,コードをステージ(git add
)して--allow-staged
をつけて実行するか選べるらしい。
cargo fix --allow-dirty
formatter
-
cargo fmt
でコードをフォーマットすることができる。
rustup component add rustfmt # 一括ダウンロードの場合は不要
cargo fmt
linter
rustup component add clippy
cargo clippy
VS Codeの設定
以下をインストールする
- rust-lang.rust-analyzer: Language Server
- statiolake.vscode-rustfmt: Formatter
- dustypomerleau.rust-syntax: Syntax Highlighting
- vadimcn.vscode-lldb: Debugger
- swellaby.vscode-rust-test-adapter: Test Runner
- tamasfe.even-better-toml: TOML Highlighting
settings.json
"[rust]": {
"editor.defaultFormatter": "statiolake.vscode-rustfmt",
"editor.formatOnSave": true,
"editor.semanticHighlighting.enabled": false
}