> For the complete documentation index, see [llms.txt](https://zenofchain.gitbook.io/sway-bian-cheng-yu-yan-geng-xin-zhong-the-sway-programming-languageupdatin/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zenofchain.gitbook.io/sway-bian-cheng-yu-yan-geng-xin-zhong-the-sway-programming-languageupdatin/3.sway-bian-cheng-lei-xing-sway-program-types/3.2-ku-libraries.md).

# 3.2 库 (Libraries)

Libraries in Sway are files used to define new common behavior. The most prominent example of this is the [Sway Standard Library](https://fuellabs.github.io/sway/v0.38.0/book/introduction/standard_library.html) that is made implicitly available to all Forc projects created using `forc new`.

### 编写库 (Writing Libraries)

Libraries are defined using the `library` keyword at the beginning of a file, followed by a name so that they can be imported.

库的定义是在文件的开头使用`library`关键字，后面跟一个名字，这们就可以被导入。

```
library;

// library code

```

A good reference library to use when learning library design is the [Sway Standard Library](https://fuellabs.github.io/sway/v0.38.0/book/introduction/standard_library.html). For example, the standard library offers an [implementation](https://github.com/FuelLabs/sway/blob/master/sway-lib-std/src/option.sw) of `enum Option<T>` which is a generic type that represents either the existence of a value using the variant `Some(..)` or a value's absence using the variant `None`. The [Sway file implementing `Option<T>`](https://github.com/FuelLabs/sway/blob/master/sway-lib-std/src/option.sw) has the following structure:

在学习库的设计时，有一个很好的参考：[Sway标准库](https://fuellabs.github.io/sway/v0.38.0/book/introduction/standard_library.html)。例如，标准库提供了一个`enum Option<T>`的[实现](https://github.com/FuelLabs/sway/blob/master/sway-lib-std/src/option.sw)，它是一个通用类型，使用变量`Some(..)`表示一个值的存在，或者使用变量`None`表示一个值的不存在。实现`Option<T>` [的Sway文件](https://github.com/FuelLabs/sway/blob/master/sway-lib-std/src/option.sw)有以下结构：

* The `library` keyword:\
  `library` 关键字：

```
library;

```

* A `use` statement that imports `revert` from another library *inside* the standard library:\
  从标准库以外的另一个库中导入 `revert`的 `use`语句：

```
use ::revert::revert;

```

* The `enum` definition which starts with the keyword `pub` to indicate that this `Option<T>` is publically available *outside* the `option` library:\
  以关键字 `pub`开始的 `enum`定义，表明这个 `Option<T>`在 `Option`库之外是公开可用的：

```
pub enum Option<T> {
    // variants
}
```

* An `impl` block that implements some methods for `Option<T>`:\
  实现了 `Option<T>`的一些方法的一个 `impl`区块，：

```
impl<T> Option<T> {

    fn is_some(self) -> bool {
        // body of is_some
    }

    // other methods
}

```

Now that the library `option` is fully written, and because `Option<T>` is defined with the `pub` keyword, we are now able to import `Option<T>` using `use std::option::Option;` from any Sway project and have access to all of its variants and methods. That being said, `Option` is automatically available in the [standard library prelude](https://fuellabs.github.io/sway/v0.38.0/book/introduction/standard_library.html#standard-library-prelude) so you never actually have to import it manually.

现在库`option`已经完全编好了，而且因为`Option<T>`是用`pub`关键字定义的，我们现在可以使用`use std::option::Option;`从任何Sway项目中导入`Option<T>`，并可以访问它的所有变体和方法。也就是说，`Option`在[标准库前置条件](https://fuellabs.github.io/sway/v0.38.0/book/introduction/standard_library.html#standard-library-prelude)中是自动可用的，所以你实际上从来不需要手动导入它。

Libraries are composed of just a `Forc.toml` file and a `src` directory, unlike contracts which usually contain a `tests` directory and a `Cargo.toml` file as well. An example of a library's `Forc.toml`:

库只由一个`Forc.toml`文件和一个`src`目录组成，不像合约通常包含一个`tests`目录和一个`Cargo.toml`文件。以一个库的 `Forc.toml` 为例：

```
[project]
authors = ["Fuel Labs <contact@fuel.sh>"]
entry = "lib.sw"
license = "Apache-2.0"
name = "my_library"

[dependencies]

```

which denotes the authors, an entry file, the name by which it can be imported, and any dependencies.

说明了作者，一个入口文件，可以被导入的名称，以及任何依赖。

For large libraries, it is recommended to have a `lib.sw` entry point re-export all other sub-libraries.

对于大型的库，建议有一个`lib.sw`入口点来重新输出所有其他子库。

The `mod` keyword registers a submodule, making its items (such as functions and structs) accessible from the parent library. If used at the top level it will refer to a file in the `src` folder and in other cases in a folder named after the library in which it is defined.

`mod`关键字注册了一个子模块，使其项目（如函数和结构）可以从父库中访问。如果在顶层使用，它将指向`src`文件夹中的一个文件，在其他情况下则指向以其定义的库来命名的文件夹。

For example, the `lib.sw` of the standard library looks like:

例如，标准库的`lib.sw`看起来像：

```
library;

mod block;
mod storage;
mod constants;
mod vm;
// .. Other deps

```

with other libraries contained in the `src` folder, like the vm library (inside of `src/vm.sw`):

与其他包含在 `src`文件夹中的库，如vm库（在 "src/vm.sw "内）：

```
library;

mod evm;
// ...

```

and it's own sub-library evm located in `src/vm/evm.sw`:

和它自己的子库evm，位于`src/vm/evm.sw`中：

```
library;

// ...

```

### 使用库 (Using Libraries)

There are two types of Sway libraries, based on their location and how they can be imported.

根据位置和其导入方式，共计有两种类型的Sway库，

#### 内部库 (Internal Libraries)

Internal libraries are located within the project's `src` directory alongside `main.sw` or in the appropriate folders as shown below:

内部库位于项目的`src`目录下，与`main.sw`并列，或位于适当的文件夹中，如下所示：

```
$ tree
.
├── Cargo.toml
├── Forc.toml
└── src
    ├── internal_lib.sw
    ├── main.sw
    └── internal_lib
        └── nested_lib.sw

```

As `internal_lib` is an internal library, it can be imported into `main.sw` as follows:

由于`internal_lib`是一个内部库，它可以被导入到`main.sw`中，方法如下：

* Use the `mod` keyword followed by the library name to make the internal library a dependancy\
  使用`mod`关键字，后面跟上库的名字，使内部库成为依赖
* Use the `use` keyword with a `::` separating the name of the library and the imported item(s)\
  使用`use`关键字，用`::`分隔库名和导入的项目。

```
mod internal_lib; // Assuming the library name in `internal_lib.sw` is `internal_lib`

use internal_lib::mint;

// `mint` from `internal_library` is now available in this file

```

#### 外部库 (External Libraries)

External libraries are located outside the main `src` directory as shown below:

外部库位于主`src`目录之外，如下所示：

```
$ tree
.
├── my_project
│   ├── Cargo.toml
│   ├── Forc.toml
│   └─── src
│       └── main.sw
│
└── external_lib
    ├── Cargo.toml
    ├── Forc.toml
    └─── src
        └── lib.sw

```

As `external_lib` is outside the `src` directory of `my_project`, it needs to be added as a dependency in the `Forc.toml` file of `my_project`, by adding the library path in the `dependencies` section as shown below, before it can be imported:

由于 `external_lib`在 `my_project`的 `src`目录之外，它需要在 `my_project`的 `Forc.toml`文件中被添加为一个依赖，在 `dependencies`部分添加库的路径，才能被导入，如下图所示，：

```
[dependencies]
external_library = { path = "../external_library" }

```

Once the library dependency is added to the `toml` file, you can import items from it as follows:

一旦库的依赖被添加到`toml`文件中，你就可以按以下方式导入项目：

* Make sure the item you want imported are declared with the `pub` keyword (if applicable, for instance: `pub fn mint() {}`)\
  确保你想导入的项目是用`pub`关键字声明的（如果适用，例如：`pub fn mint() {}`)
* Use the `use` keyword to selectively import items from the library\
  使用`use`关键字，有选择地从库中导入项目

```
use external_library::mint;

// `mint` from `external_library` is now available in this file

```

Wildcard imports using `*` are supported, but it is generally recommended to use explicit imports where possible.

支持使用`*`的通配符导入，但一般建议尽可能使用显式/明确导入。

> **Note**: the standard library is implicitly available to all Forc projects, that is, you are not required to manually specify `std` as an explicit dependency in `Forc.toml`.\
> **注意**：标准库对所有Forc项目都是隐式的，也就是说，你不需要在`Forc.toml`中手动指定`std`作为显式依赖。

### 参考Sway库 (Reference Sway Libraries)

The repository [`sway-libs`](https://github.com/FuelLabs/sway-libs/) is a collection of external libraries that you can import and make use of in your Fuel applications. These libraries are meant to be learning references of common use-cases valuable for dapp development.

[`sway-libs`库](https://github.com/FuelLabs/sway-libs/)是一个外部库的集合，你可以在你的Fuel应用中导入和使用。这些库的目的是为了学习参考对DApp开发有价值的常见用例。

Some Sway Libraries to try out:\
一些可以尝试的Sway库：

* [Binary Merkle Proof](https://github.com/FuelLabs/sway-libs/tree/master/libs/merkle_proof)
* [Non-Fungible Token](https://github.com/FuelLabs/sway-libs/tree/master/libs/nft)
* [String](https://github.com/FuelLabs/sway-libs/tree/master/libs/string)
* [Signed Integers](https://github.com/FuelLabs/sway-libs/tree/master/libs/signed_integers)
* [Unsigned Fixed Point Number](https://github.com/FuelLabs/sway-libs/tree/master/libs/fixed_point)
* [StorageMapVec](https://github.com/FuelLabs/sway-libs/tree/master/libs/storagemapvec)

#### 示例 (Example)

You can import and use a Sway Library such as the [NFT](https://github.com/FuelLabs/sway-libs/tree/master/sway_libs/src/nft) library just like any other external library.

你可以像其他外部库一样导入和使用Sway库，如[NFT](https://github.com/FuelLabs/sway-libs/tree/master/sway_libs/src/nft)库。

```
use sway_libs::nft::{
    mint,
    transfer,
    owner_of,
    approve,
};

```

Once imported, you can use the following basic functionality of the library in your smart contract:\
一旦导入，你可以在你的智能合约中使用该库的以下基本功能：

* Minting tokens\
  铸造代币
* Transfering tokens\
  转移代币
* Retrieving owner of a token\
  检索代币的所有者
* Approving users to transfer a token\
  批准用户转让代币
