Rust入門:インストールからHello World, Cargoの使用まで
この記事について
自身がRust初心者であり、学んでいくためのメモでもあります。
- macOS, Linuxを使用している
- ターミナル・シェル・コマンド操作が理解できる
- ソースコードのエディタが使える
ことを前提としています。
ここでは、
- インストール
- Hello World
- Cargoを使ったプロジェクト管理
まで行います。
インストール
インストールは簡単です。以下のコマンドを実行します。% 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を出力するプログラムを作成します。
プロジェクトディレクトリを作成
% 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のビルドシステム兼、パッケージマネージャです。
プロジェクト作成
% cargo new hello_cargo --bin
Created binary (application) `hello_cargo` package
% cd hello_cargo
--bin
引数が、 ライブラリではなく実行可能なアプリケーション(バイナリ)を作成します。
git
リポジトリも作成されます。
(2021/09/30 追記)現在は--bin
引数がなくてもバイナリが作成されます。その代わり、ライブラリを作成したい場合は--lib
を指定する必要があります。
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コードの実行を速くしてくれますが、 オンにするとプログラムをコンパイルする時間が延びます。
Author And Source
この問題について(Rust入門:インストールからHello World, Cargoの使用まで), 我々は、より多くの情報をここで見つけました https://zenn.dev/usk2000/articles/332201fbd55e28著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Collection and Share based on the CC protocol