😺

Rustを始めよう-環境構築からHello, World!まで-

2023/02/12に公開

最近気になってしょうがないRustをインストールしてみた。Mac M1チプへのインストール手順の備忘録です。

Rust Documrnts

公式ドキュメント https://www.rust-lang.org/ja/tools/install
Rust tutoril https://tourofrust.com/00_ja.html

動作確認環境

  • MacBook Pro (13-inch, M1, 2020)
  • チップ Apple M1
  • メモリ 16GHz
  • macOS Monterey (12.1)

インストール

rustupをインストールします。rustpuは、開発やビルドを行うためのツール一式をまとめてインストールできるインストーラーです。rustupをインストールすると、コンパイラのrustcやパッケージマネージャーのcargoも一緒にインストールされます。
こちらのサイトでも簡潔なインストール手順が日本語で読めます。

Mac(Linux)なら次のコマンドでインストールできる。

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

インストールが始まって、1箇所だけオプションの選択があるが「1(default)」を選択する。

info: downloading installer
Welcome to Rust!

This will download and install the official compiler for the Rust
programming language, and its package manager, Cargo.

Rustup metadata and toolchains will be installed into the Rustup
home directory, located at:

  /Users/[USER NAME]/.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory is located at:

  /Users/[USER NAME]/.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added to
Cargo's bin directory, located at:

  /Users/[USER NAME]/.cargo/bin

This path will then be added to your PATH environment variable by
modifying the profile files located at:

  /Users/[USER NAME]/.profile
  /Users/[USER NAME]/.zshenv

You can uninstall at any time with rustup self uninstall and
these changes will be reverted.

Current installation options:
   default host triple: aarch64-apple-darwin
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

1 (default)を選択

 stable-aarch64-apple-darwin installed - rustc 1.67.1 (d5a82bbd2 2023-02-07)

Rust is installed now. Great!

To get started you may need to restart your current shell.
This would reload your PATH environment variable to include
Cargo's bin directory ($HOME/.cargo/bin).

To configure your current shell, run:
source "$HOME/.cargo/env"

Rust is installed now. Great! が出たが、まだPATHが通ってない。
PATHを通すためにsource "$HOME/.cargo/env"を実行しろとあるので実行する。

source "$HOME/.cargo/env"

または、ターミナルを再起動でもいい。rustupをインストールすると、.zshenvに.cargo/envの呼び出し追加されていて、.cargo/envにPATHが設定されている。

.zshenv
. "$HOME/.cargo/env"
.cargo/env
case ":${PATH}:" in
    *:"$HOME/.cargo/bin":*)
        ;;
    *)
        # Prepending path in case a system-installed rustc needs to be overridden
        export PATH="$HOME/.cargo/bin:$PATH"
        ;;
esac

バージョン確認ができればOK

rustc --version
#rustc 1.67.1 (d5a82bbd2 2023-02-07)

rustcとcargoのバージョンも確認します。

rustc --version
#rustc 1.67.1 (d5a82bbd2 2023-02-07)

cargo --version
#cargo 1.67.1 (8ecd4f20a 2023-01-10)

Hello, World!

任意のプロジェクトディレクトを作って、最初のRustプログラムmain.rsを書いていきます。

mkdir hello_world
cd hello_world
touch main.rs

main.rsの記述。

main.rs
fn main() {
    // 世界よ、こんにちは
    println!("Hello, world!");
}

コンパイルすると実行ファイルが作成される

rustc main.rs
ll
#total 944
#-rwxr-xr-x  1 dc  staff  479073  2 11 19:19 main*
#-rw-r--r--  1 dc  staff      80  2 11 19:18 main.rs

実行する

./main
#Hello, world!

おめでとうございます。

Hello, cargo!

ビルドシステム兼パッケージマネージャーcargoを使って初めてのプロジェクトを作成します。
任意のディレクトリに移動し、プロジェクトhello_cargoを作成します。(hello_cargoディレクトリが作成されます。)

//プロジェクト作成
cargo new hello_cargo
#   Created binary (application) `hello_cargo` package

//生成されたディレクトリに移動する
cd hello_cargo/

//treeでファイル構成を見てみます
tree
#.
#├── Cargo.toml
#└── src
#    └── main.rs

//隠しファイルも見てみるとgitがイニシャライズされているっぽい
ll -a
#total 16
#drwxr-xr-x  6 dc  staff  192  2 11 19:34 ./
#drwxr-xr-x  4 dc  staff  128  2 11 19:34 ../
#drwxr-xr-x  9 dc  staff  288  2 11 19:37 .git/
#-rw-r--r--  1 dc  staff    8  2 11 19:34 .gitignore
#-rw-r--r--  1 dc  staff  180  2 11 19:34 Cargo.toml
#drwxr-xr-x  3 dc  staff   96  2 11 19:34 src/

公式Documentより もし、すでに存在するGitリポジトリの中でcargo newを実行したなら、Git関連のファイルは作られません。 とのこと。
ファイルの中身を見てみます。
Cargo.tomlはcargoの設定フォーマットです。[dependecies]にインポートするパッケージ情報を記載ます。(パッケージのことをRustではクレートと呼ぶ)

Cargo.toml
[package]            //セクションヘッダー. 以降の文がパッケージを設定する
name = "hello_cargo" //パッケージ名
version = "0.1.0"    //パッケージバージョン
edition = "2021"     //使用するRustのエディション

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]       //プロジェクトの依存を列挙するセッション

今回もmain.rsの中身はシンプルです。

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

cargoグロジェクトをビルドすると、実行ファイル./target/debug/hello_cargoが生成されます。

//プロジェクトをビルドする
cargo build
#   Compiling hello_cargo v0.1.0 (/Users/dc/Project/work/rust/hello_cargo)
#    Finished dev [unoptimized + debuginfo] target(s) in 0.64s

//生成されたファイル構成を確認する
tree
#.
#├── Cargo.lock
#├── Cargo.toml
#├── src
#│   └── main.rs
#└── target
#    ├── CACHEDIR.TAG
#    └── debug
#        ├── build
#        ├── deps
#        │   ├── hello_cargo-9d512699b174c2b9
#        │   ├── hello_cargo-9d512699b174c2b9.1m5sq4oxzz4uvdc4.rcgu.o
#        │   ├── hello_cargo-9d512699b174c2b9.1s2ipxglnt6kghh1.rcgu.o
#        │   ├── hello_cargo-9d512699b174c2b9.3hmtqkofaqlot9yq.rcgu.o
#        │   ├── hello_cargo-9d512699b174c2b9.4c4pubheg6plkmfi.rcgu.o
#        │   ├── hello_cargo-9d512699b174c2b9.4q8liorvwpxm0pxx.rcgu.o
#        │   ├── hello_cargo-9d512699b174c2b9.5cqwgyqh4lhaxg8a.rcgu.o
#        │   └── hello_cargo-9d512699b174c2b9.d
#        ├── examples
#        ├── hello_cargo
#        ├── hello_cargo.d
#        └── incremental
#            └── hello_cargo-3pb2h58nrz3gf
#                ├── s-gi5khk4eaf-7bh0df-1ljf30hhbtwnx
#                │   ├── 1m5sq4oxzz4uvdc4.o
#                │   ├── 1s2ipxglnt6kghh1.o
#                │   ├── 3hmtqkofaqlot9yq.o
#                │   ├── 4c4pubheg6plkmfi.o
#                │   ├── 4q8liorvwpxm0pxx.o
#                │   ├── 5cqwgyqh4lhaxg8a.o
#                │   ├── dep-graph.bin
#                │   ├── query-cache.bin
#                │   └── work-products.bin
#                └── s-gi5khk4eaf-7bh0df.lock

実行してみます。

./target/debug/hello_cargo
#Hello, world!

成功しました。おめでとうございます。
でも、いちいち実行ファイルを叩くのは面倒です。ビルドと実行を一括で行ってくれるコマンドがrunです。

cargo run
#    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
#     Running `target/debug/hello_cargo`
#Hello, world!

その他にもcheckというコマンドがあります。ソースコードがコンパイルできるか、実行ファイル生成のステップを省いて実行されるので、コードを継続的に書きながらチェックという工程では重宝されそうです。
コマンドをまとめておきます。

コマンド 概要
cargo new プロジェクトを作成する
cargo build プロジェクトをビルド->実行ファイルを生成
cargo run プロジェクトをビルド->実行ファイルを生成->実行
cargo check プロジェクトをビルド(実行ファイルを生成せずにエラーがないか確認できる)

rustupのアップデートとアンインストール

次のコマンドでアップデートとアンインストールができます。

//rustupアップデート
rustup update

//rustupアンインストール
rustup self uninstall

Discussion