CLOVER🍀

That was when it all began.

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.tomlのeditionずいうのは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.tomlのdependenciesに远加されおいたす。

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の蚭定も行ったので、これから少しず぀慣れおいこうず思いたす。