ライブラリの使用

RustRustBeginner
オンラインで実践に進む

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Rust でクレートを新しいライブラリにリンクするには、rustc コマンドの --extern フラグを使用し、そのすべての項目をライブラリと同じ名前のモジュールの下にインポートできます。

注: 実験でファイル名が指定されていない場合は、好きなファイル名を使用できます。たとえば、main.rs を使用して、rustc main.rs &&./main でコンパイルして実行できます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/ProjectManagementandOrganizationGroup(["Project Management and Organization"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/ProjectManagementandOrganizationGroup -.-> rust/cargo_crates("Cargo and Crates") subgraph Lab Skills rust/function_syntax -.-> lab-99338{{"ライブラリの使用"}} rust/expressions_statements -.-> lab-99338{{"ライブラリの使用"}} rust/method_syntax -.-> lab-99338{{"ライブラリの使用"}} rust/cargo_crates -.-> lab-99338{{"ライブラリの使用"}} end

ライブラリの使用

この新しいライブラリにクレートをリンクするには、rustc--extern フラグを使用できます。その後、そのすべての項目は、ライブラリと同じ名前のモジュールの下にインポートされます。このモジュールは一般的に、他の任意のモジュールと同じように動作します。

// extern crate rary; // Rust 2015 エディション以前では必要な場合があります

fn main() {
    rary::public_function();

    // エラー!`private_function` は非公開です
    //rary::private_function();

    rary::indirect_access();
}
## library.rlib がコンパイル済みライブラリのパスで、ここでは同じディレクトリにあると仮定します。
$ rustc executable.rs --extern rary=library.rlib &&./executable
rary の `public_function()` を呼び出しました
rary の `indirect_access()` を呼び出しました。それは
> rary の `private_function()` を呼び出しました

まとめ

おめでとうございます!ライブラリの使用という実験を完了しました。LabEx でさらに多くの実験を行って、スキルを向上させることができます。