3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rust】Library crateの使い方

Last updated at Posted at 2023-05-06

crates.ioのcrateを使う

crates.ioは、Rustで使えるutility crateをまとめたサイトです。
たとえば、乱数を生成するrandを導入する場合、以下の手順になります。

1)下図のrand = "0.8.5"をコピーする

2)Cargo.tomldependenciesに登録する

Cargo.toml
[package]
name = "lib_demo"
version = "0.1.0"
edition = "2021"

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

[dependencies]
rand = "0.8.5"

3)buildする

.cmd
cargo build

4)useで参照する

use rand::Rng;

pub fn gen_ran() -> u8 {
  let mut rng = rand::thread_rng();
  let n: u8 = rng.gen();
  n
}

自作のライブラリを使う

自作したライブラリをGitHubに登録して、それをrust appで使用する方法です。

1)ライブラリの作成

cargoを使ったプロジェクトは、appとlibがあり、ライブラリとしてプロジェクトを作る場合は、以下のコマンドで作成します。

.cmd
cargo new --lib [name]

ちなみに、アプリケーションとしてプロジェクトを作成する場合は、

.cmd
cargo new [name]

2)lib.rsに関数を作る

ライブラリは、lib.rsが実行ファイル(最初にcallされるファイル)になります。ここに、publicで関数を記述することで、ライブラリとして外部から呼び出すことができます。

lib.rs
mod generator;

pub fn print_random_number() {
  let n = generator::gen_ran();
  println!("Random u8: {}", n);
}

3)GitHubにリポジトリを作成する

publicリポジトリを作成して、プロジェクトをコミットします。

4)ライブラリとして別のプロジェクトから呼び出す

ライブラリを使いたいプロジェクトのCargo.tomldependenciesに登録します。
gitに指定しているurlは、リポジトリのurlです。

Cargo.toml
[package]
name = "rust-lesson"
version = "0.1.0"
edition = "2021"

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

[dependencies]
lib_demo = {git = "https://github.com/xxxxx/rust-lib-demo"}

5)buildする

.cmd
cargo build

6)extern crateで参照する

登録したライブラリは、extern crateで参照します。

main.rs
extern crate lib_demo;

fn main() {
  lib_demo::print_random_number();
}

参考

この記事は、こちらの備忘録として書いています。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?