👌

Rust入門:インストールからHello World, Cargoの使用まで

2021/09/16に公開
2

この記事について

自身がRust初心者であり、学んでいくためのメモでもあります。

  • macOS, Linuxを使用している
  • ターミナル・シェル・コマンド操作が理解できる
  • ソースコードのエディタが使える
    ことを前提としています。

https://www.rust-lang.org/ja/

ここでは、

  • インストール
  • Hello World
  • Cargoを使ったプロジェクト管理

まで行います。

インストール

https://www.rust-lang.org/ja/tools/install
インストールは簡単です。以下のコマンドを実行します。

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

途中、選択肢が出てきます。

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

デフォルトの設定を用いるので、1を入力してエンターを押します。
インストールが完了したら、新しいシェルにします。

アップデート

% rustup update

バージョン確認

% rustc --version
rustc 1.55.0 (c8dfcfe04 2021-09-06)
% cargo --version
cargo 1.55.0 (32da73ab1 2021-08-23)

Hello World

Hello Worldを出力するプログラムを作成します。
https://doc.rust-jp.rs/book-ja/ch01-02-hello-world.html

プロジェクトディレクトリを作成

% mkdir -p workspace/rust/helloworld
% cd workspace/rust/helloworld

コードを書く

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

コンパイルと実行

% rustc main.rs
% ./main
Hello, world!

println!!はRustのマクロ関数を呼び出しています。

Cargoを使ってプロジェクトを管理

Cargoは、Rustのビルドシステム兼、パッケージマネージャです。
https://doc.rust-jp.rs/book-ja/ch01-03-hello-cargo.html

プロジェクト作成

% cargo new hello_cargo --bin
     Created binary (application) `hello_cargo` package
% cd hello_cargo

--bin引数が、 ライブラリではなく実行可能なアプリケーション(バイナリ)を作成します。
gitリポジトリも作成されます。
(2021/09/30 追記)現在は--bin引数がなくてもバイナリが作成されます。その代わり、ライブラリを作成したい場合は--libを指定する必要があります。
https://doc.rust-lang.org/cargo/getting-started/first-steps.html

Cargo.tomlの中身

[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[package]: パッケージの内容
[dependencies]: 依存関係
src/配下にRustのソースコードがあることが期待されています。

ビルド

% cargo build
   Compiling hello_cargo v0.1.0 (/path/to/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.80s

target/debug/hello_cargoに実行ファイルがある

ビルドから実行まで

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

コンパイルできるかチェック

% cargo check
    Checking hello_cargo v0.1.0 (/path/to/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.12s

リリースビルド

% cargo build --release
  • 最適化を行なってコンパイルすることができます。
  • target/debugではなく、 target/releaseに実行可能ファイルを作成します。
  • 最適化は、Rustコードの実行を速くしてくれますが、 オンにするとプログラムをコンパイルする時間が延びます。

Discussion

とがとが

ちなみに,もともと $ cargo new はデフォルトで $ cargo new --lib と同じだったので,ライブラリクレートではなくバイナリクレートを作る場合 $ cargo new --bin と明示的に --bin を付ける必要があった(日本語版 the book でもそうなっている)のですが,今は $ cargo new がデフォルトで $ cargo new --bin と同じになったので,--bin を付ける必要はありません(英語版 the book ではそうなっています).

YuusukeYuusuke

ご指摘ありがとうございます!後ほど修正します。