以下の内容はhttps://kazuhira-r.hatenablog.com/entry/2025/01/01/115017より取得しました。


Ubuntu Linux 24.04 LTSでRustを始める(+Emacs lsp-mode)

これは、なにをしたくて書いたもの?

Rustの勉強を始めようと思いまして、まずはインストールからということで。

Rust

RustのWebサイトはこちら。

Rust Programming Language

Rustの特徴は以下のように書かれています。

  • パフォーマンス
  • 信頼性
    • 豊富な型システムと所有権モデルにより、メモリーの安全性とスレッドの安全性を保証する
    • コンパイル時に多くのバグを排除できる
  • 生産性
    • ドキュメント、コンパイラー、パッケージマネージャー、ビルドツール、エディターのサポートやフォーマッターなどが揃っている

ドキュメントはここを見ていくようです。

Learn Rust - Rust Programming Language

標準ライブラリーのドキュメントはこちら。

std - Rust

まずはここから始めましょう。

Getting Started - The Rust Programming Language

環境

今回の環境はこちら。Ubuntu Linux 24.04 LTSです。

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 24.04.1 LTS
Release:        24.04
Codename:       noble


$ uname -srvmpio
Linux 6.8.0-51-generic #52-Ubuntu SMP PREEMPT_DYNAMIC Thu Dec  5 13:09:44 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux

Rustをインストールする

最初はRustのインストールからですね。Rustのインストールは、rustupというCLIを使って行うようです。

Installation - The Rust Programming Language

Install Rust - Rust Programming Language

Getting started - Rust Programming Language

というわけで、まずはrustupのインストールからですね。

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

いろいろ表示されます。

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:

  $HOME/.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory is located at:

  $HOME/.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:

  $HOME/.cargo/bin

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

  $HOME/.profile
  $HOME/.bashrc

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

Current installation options:


   default host triple: x86_64-unknown-linux-gnu
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with standard installation (default - just press enter)
2) Customize installation
3) Cancel installation

よく見ると、rustupやCargoが使うディレクトリが表示されています。

また最後に選択肢が表示されていますが、そのままEnterを押してデフォルトの1を選択。

インストールが完了しました。

info: profile set to 'default'
info: default host triple is x86_64-unknown-linux-gnu
info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2024-11-28, rust version 1.83.0 (90b35a623 2024-11-26)
info: downloading component 'cargo'
info: downloading component 'clippy'
info: downloading component 'rust-docs'
 16.4 MiB /  16.4 MiB (100 %)  10.8 MiB/s in  1s ETA:  0s
info: downloading component 'rust-std'
 26.1 MiB /  26.1 MiB (100 %)  10.9 MiB/s in  3s ETA:  0s
info: downloading component 'rustc'
 69.3 MiB /  69.3 MiB (100 %)  10.1 MiB/s in  8s ETA:  0s
info: downloading component 'rustfmt'
info: installing component 'cargo'
info: installing component 'clippy'
info: installing component 'rust-docs'
 16.4 MiB /  16.4 MiB (100 %)   4.3 MiB/s in  3s ETA:  0s
info: installing component 'rust-std'
 26.1 MiB /  26.1 MiB (100 %)   8.7 MiB/s in  3s ETA:  0s
info: installing component 'rustc'
 69.3 MiB /  69.3 MiB (100 %)   9.6 MiB/s in  8s ETA:  0s
info: installing component 'rustfmt'
info: default toolchain set to 'stable-x86_64-unknown-linux-gnu'

  stable-x86_64-unknown-linux-gnu installed - rustc 1.83.0 (90b35a623 2024-11-26)


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, you need to source
the corresponding env file under $HOME/.cargo.

This is usually done by running one of the following (note the leading DOT):
. "$HOME/.cargo/env"            # For sh/bash/zsh/ash/dash/pdksh
source "$HOME/.cargo/env.fish"  # For fish

bashの場合、$HOME/.bashrcの最後に以下の行が追加されていました。

. "$HOME/.cargo/env"

このため、シェルにログインしなおすとrustupが使えるようになっています。

$ rustup --version
rustup 1.27.1 (54dd3d00f 2024-04-24)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.83.0 (90b35a623 2024-11-26)`

rustupだけではなく、rustcなどもですね。

$ rustc --version
rustc 1.83.0 (90b35a623 2024-11-26)


$ cargo --version
cargo 1.83.0 (5ffbef321 2024-10-29)

このあたり、バージョンが揃っているんですね。

rustupでインストールされたツールをアップデートするにはrustup updateを実行するようです。

$ rustup update

Installation - The Rust Programming Language

rustup自体をアプデートするにはrustup self updateを実行するようです。

$ rustup self update

Basic usage / Keeping rustup up to date

Hello World

なにはともあれ「Hello World」。

Hello, World! - The Rust Programming Language

ひとまずそのまま書き写してみます。

main.rs

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

コンパイル

$ rustc main.rs

実行ファイルができました。

$ ll
合計 3772
drwxrwxr-x 2 xxxxx xxxxx    4096 12月 31 22:09 ./
drwxrwxr-x 3 xxxxx xxxxx    4096 12月 31 21:56 ../
-rwxrwxr-x 1 xxxxx xxxxx 3849096 12月 31 22:09 main*
-rw-rw-r-- 1 xxxxx xxxxx      45 12月 31 22:08 main.rs

実行。

$ ./main
Hello, world!

動きました。

ひとまず、初めてのRustコードを書いて動かしてみました。

rust-analyzer+Emacs lsp-modeを使う

Getting Startedではこの後にCargoの紹介に移るのですが、先にエディターをなんとかしたいと思います。

自分はEmacsを使っているのでlsp-modeと組み合わせたいのですが、Language Serverにはrust-analyzerを使うようです。

rust-analyzer

Rust (rust-analyzer) - LSP Mode - LSP support for Emacs

rust-analyzerもrustupでインストールできます。

$ rustup component add rust-analyzer

Components - The rustup book

あとはrust-modeをインストールして以下を追加(lsp-modeは設定済みとします)。

;; rust
(use-package lsp-mode
  :ensure t
  :commands (lsp lsp-deferred)
  :hook (rust-mode . lsp-deferred))

rust-modeはこちら。

GitHub - rust-lang/rust-mode: Emacs configuration for Rust

ちなみに、使ってみた感じだとCargo.tomlがないと動かない感じがするので先に進みます。

Cargoでプロジェクトを作成する

次はCargoを使ってみましょう。

Hello, Cargo! - The Rust Programming Language

CargoはRustのビルドツールおよびパッケージマネージャーだそうです。

プロジェクトの作成。

$ cargo new hello-cardo

プロジェクト内に移動。

$ cd hello-cardo

作成されたプロジェクトの中身。

$ tree
.
├── Cargo.toml
└── src
    └── main.rs

2 directories, 2 files

Cargo.toml

[package]
name = "hello-cardo"
version = "0.1.0"
edition = "2021"

[dependencies]

src/main.rs

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

Cargo.tomleditionというのはRustの言語のバージョンのようなものみたいですね。

Introduction - The Rust Edition Guide

現在の最新のエディションは2021で、rustcのデフォルトは2015のようです。

        --edition 2015|2018|2021|2024
                        Specify which edition of the compiler to use when
                        compiling code. The default is 2015 and the latest
                        stable edition is 2021.

では、ビルドしてみます。

$ cargo build

こんな表示が出て

$ cargo build
   Compiling hello-cardo v0.1.0 ($HOME/hello-cardo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.18s

ビルド結果はtarget/debug配下にできるようなので、これを実行。

$ ./target/debug/hello-cardo
Hello, world!

OKですね。

carog runでも実行できるようです。

$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/hello-cardo`
Hello, world!

1度targetディレクトリをcargo cleanで削除して

$ cargo clean
     Removed 21 files, 7.5MiB total

再度cargo runすると、コンパイルから実行まで一気に行うようです。

$ cargo run
   Compiling hello-cardo v0.1.0 (/$HOME/hello-cardo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.21s
     Running `target/debug/hello-cardo`
Hello, world!

ちなみに、表示を見ると気づきますがこれはデバッグビルド(開発用)です。

リリースビルドを作成するには、--releaseをつけてビルドします。

$ cargo build --release
   Compiling hello-cardo v0.1.0 ($HOME/hello-cardo)
    Finished `release` profile [optimized] target(s) in 0.58s

ビルド結果はtarget/release配下にできます。

$ ./target/release/hello-cardo
Hello, world!

リリースビルドは最適化を行うようなのでアプリケーションの実行速度は向上するようですが、代わりにコンパイルが長くなるという
トレードオフがあるようです。

必要に応じて開発用とリリース用のプロファイルを使い分けていくようです。たとえば、ベンチマークをとる時には--release
付けてビルドする必要があります。

依存関係を追加する

ドキュメントでのCargoを使ったGetting Startedはここで終わるのですが、こちらには依存関係を追加する例もあるので試してみましょう。

Getting started - Rust Programming Language

ferris-saysという依存関係を追加します。

$ cargo add ferris-says

いろいろ追加されました。

    Updating crates.io index
      Adding ferris-says v0.3.2 to dependencies
             Features:
             - clippy
    Updating crates.io index
     Locking 11 packages to latest compatible versions
      Adding aho-corasick v1.1.3
      Adding ferris-says v0.3.2
      Adding memchr v2.7.4
      Adding regex v1.11.1
      Adding regex-automata v0.4.9
      Adding regex-syntax v0.8.5
      Adding smallvec v1.13.2
      Adding smawk v0.3.2
      Adding textwrap v0.16.1
      Adding unicode-linebreak v0.1.5
      Adding unicode-width v0.1.14

Cargo.tomldependenciesに追加されています。

Cargo.toml

[package]
name = "hello-cardo"
version = "0.1.0"
edition = "2021"

[dependencies]
ferris-says = "0.3.2"

この追加する依存関係のことをcrate(クレート)と呼ぶようです。

追加したクレートのドキュメントに書かれているコード例を、そのまま使ってみます。

ferris-says

こんな感じですね。

src/main.rs

use ferris_says::say;
use std::io::{stdout, BufWriter};

fn main() {
    let out = "Hello fellow Rustaceans!";
    let width = 24;

    let mut writer = BufWriter::new(stdout());
    say(out, width, &mut writer).unwrap();
}

cargo runで直接実行。

$ cargo run
  Downloaded smawk v0.3.2
  Downloaded ferris-says v0.3.2
  Downloaded smallvec v1.13.2
  Downloaded unicode-linebreak v0.1.5
  Downloaded textwrap v0.16.1
  Downloaded memchr v2.7.4
  Downloaded aho-corasick v1.1.3
  Downloaded regex-syntax v0.8.5
  Downloaded regex v1.11.1
  Downloaded unicode-width v0.1.14
  Downloaded regex-automata v0.4.9
  Downloaded 11 crates (1.9 MB) in 0.33s
   Compiling memchr v2.7.4
   Compiling regex-syntax v0.8.5
   Compiling unicode-linebreak v0.1.5
   Compiling unicode-width v0.1.14
   Compiling smawk v0.3.2
   Compiling smallvec v1.13.2
   Compiling textwrap v0.16.1
   Compiling aho-corasick v1.1.3
   Compiling regex-automata v0.4.9
   Compiling regex v1.11.1
   Compiling ferris-says v0.3.2
   Compiling hello-cardo v0.1.0 ($HOME/hello-cardo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.65s
     Running `target/debug/hello-cardo`
 __________________________
< Hello fellow Rustaceans! >
 --------------------------
        \
         \
            _~^~^~_
        \) /  o o  \ (/
          '_   -   _'
          / '-----' \

初回のコマンド実行時にクレートをダウンロードしてくるみたいです。実行も無事できましたね。

Rustって依存するモジュールも一緒にビルドするんですね、と実行ログを見ながら思いました。
またcargo build --releaseをやってみると明らかに遅くなりました。ビルドに時間がかかるとは聞いたことがありましたが、今回書いた
ソースコードは数行なので確かに重たいんですね。

まあ、今回はこんなところでしょうか。

最後にlddで依存している共有ライブラリーを見ておきます。

$ ldd target/release/hello-cardo
        linux-vdso.so.1 (0x00007ffde8334000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x0000707799e99000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x0000707799800000)
        /lib64/ld-linux-x86-64.so.2 (0x0000707799ee3000)

確かに言語固有の共有ライブラリーなどはなさそうです。
※開発用ビルドでも同じ結果になりました

おわりに

Rustを始めるためにrustupをインストールして、初めてのRustのコードを書いたりしてみました。

lsp-modeの設定も行ったので、これから少しずつ慣れていこうと思います。




以上の内容はhttps://kazuhira-r.hatenablog.com/entry/2025/01/01/115017より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14