> For the complete documentation index, see [llms.txt](https://chihaolu.gitbook.io/all-in-one-solidity/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chihaolu.gitbook.io/all-in-one-solidity/part-ii-medium/chapter-13-yin-yong-imports-han-shi-ku-libraries/library.md).

# 【Library】

Library 非常類似於 `contracts`，但我們不能在裡面宣告任何的 state variables 而且我們也不可以傳送任何 ether。

使用範例：

```solidity
pragma solidity ^0.8.11;

library Lib {  
  function add(uint a, uint b) pure internal returns(uint) {
    return a + b;
  }
}

contract A {
  using Lib for uint;

  function add(uint a, uint b) pure external returns(uint) {
    return a.add(b);
  }
}
```

在 Solidity 裡面有兩種 Libraries 類型：

* deployed：有自己的合約地址，可以被智能合約在執行時調用
* embedded：當所有的 library 函數皆為 `internal`；沒有自己的合約地址，會變成我們合約的一部分程式碼。

```solidity
// Embedded (function is internal)
library Lib_Embedded {  
  function add(uint a, uint b) pure internal returns(uint) {
    return a + b;
  }
}

//Deployed (function is public)
library Lib_Deployed {  
  function add(uint a, uint b) pure public returns(uint) {
    return a + b;
  }
}
```

#### Libraries & Using ... for

* Libraries使用上有點類似Contracts
* 程式碼運用了`DELEGATECALL` 的特性可以被重複使用
* Libraries運作上類似直接從「呼叫引入處」貼上來源程式碼至合約內
* Libraries不具有自我摧毀的功能，因此從定義上不能被摧毀
* 相關限制（在未來版本有可能會改變）
  * 不具有狀態變數（State variables）
  * 不可進行繼承和被繼承
  * 不可接收Ether
