- Elixir 教程
- Elixir - 首頁
- Elixir - 概覽
- Elixir - 環境
- Elixir - 基本語法
- Elixir - 資料型別
- Elixir - 變數
- Elixir - 運算子
- Elixir - 模式匹配
- Elixir - 決策
- Elixir - 字串
- Elixir - 字元列表
- Elixir - 列表和元組
- Elixir - 關鍵字列表
- Elixir - 對映
- Elixir - 模組
- Elixir - 別名
- Elixir - 函式
- Elixir - 遞迴
- Elixir - 迴圈
- Elixir - 可列舉
- Elixir - 流
- Elixir - 結構體
- Elixir - 協議
- Elixir - 檔案 I/O
- Elixir - 程序
- Elixir - 符號
- Elixir - 推導式
- Elixir - 型別規範
- Elixir - 行為
- Elixir - 錯誤處理
- Elixir - 宏
- Elixir - 庫
- Elixir 有用資源
- Elixir - 快速指南
- Elixir - 有用資源
- Elixir - 討論
Elixir - 別名
為了方便軟體重用,Elixir 提供了三個指令 - **alias、require** 和 **import**。它還提供了一個名為 use 的宏,總結如下:
# Alias the module so it can be called as Bar instead of Foo.Bar alias Foo.Bar, as: Bar # Ensure the module is compiled and available (usually for macros) require Foo # Import functions from Foo so they can be called without the `Foo.` prefix import Foo # Invokes the custom code defined in Foo as an extension point use Foo
現在讓我們詳細瞭解每個指令。
alias
alias 指令允許您為任何給定的模組名稱設定別名。例如,如果您想為 String 模組提供一個別名 **'Str'**,您可以簡單地編寫:
alias String, as: Str
IO.puts(Str.length("Hello"))
上述程式生成以下結果:
5
為 **String** 模組提供了 **Str** 的別名。現在,當我們使用 Str 字面量呼叫任何函式時,它實際上會引用 **String** 模組。當我們使用非常長的模組名稱並希望在當前作用域中用較短的名稱替換它們時,這非常有用。
**注意** - 別名**必須**以大寫字母開頭。
別名僅在呼叫它們的**詞法作用域**內有效。例如,如果在一個檔案中包含 2 個模組,並在其中一個模組中建立別名,則該別名在第二個模組中不可訪問。
如果您將內建模組(如 String 或 Tuple)的名稱作為其他模組的別名,要訪問內建模組,您需要在前面加上 **"Elixir."**。例如,
alias List, as: String
#Now when we use String we are actually using List.
#To use the string module:
IO.puts(Elixir.String.length("Hello"))
當執行上述程式時,它會生成以下結果:
5
require
Elixir 提供宏作為超程式設計(編寫生成程式碼的程式碼)的機制。
宏是在編譯時執行和擴充套件的程式碼塊。這意味著,為了使用宏,我們需要保證其模組和實現在編譯時可用。這是透過 **require** 指令完成的。
Integer.is_odd(3)
當執行上述程式時,它將生成以下結果:
** (CompileError) iex:1: you must require Integer before invoking the macro Integer.is_odd/1
在 Elixir 中,**Integer.is_odd** 被定義為一個**宏**。此宏可用作保護。這意味著,為了呼叫 **Integer.is_odd**,我們需要 Integer 模組。
使用 **require Integer** 函式並按如下所示執行程式。
require Integer Integer.is_odd(3)
這次程式將執行並輸出:**true**。
通常,模組在使用前不需要載入,除非我們想使用該模組中可用的宏。嘗試呼叫未載入的宏將引發錯誤。請注意,與 alias 指令一樣,require 也具有詞法作用域。我們將在後面的章節中詳細討論宏。
import
我們使用 **import** 指令輕鬆訪問其他模組中的函式或宏,而無需使用完全限定的名稱。例如,如果我們想多次使用 List 模組中的 **duplicate** 函式,我們可以簡單地匯入它。
import List, only: [duplicate: 2]
在這種情況下,我們只從 List 中匯入函式 duplicate(帶引數列表長度為 2)。雖然 **:only** 是可選的,但建議使用它以避免將給定模組的所有函式匯入名稱空間。也可以使用 **:except** 作為選項,以匯入模組中的所有內容,除了函式列表之外。
**import** 指令還支援將 **:macros** 和 **:functions** 傳遞給 **:only**。例如,要匯入所有宏,使用者可以編寫:
import Integer, only: :macros
請注意,import 也像 require 和 alias 指令一樣具有**詞法作用域**。還要注意,**'匯入' 模組也 '需要' 它**。
use
雖然不是指令,但 **use** 是一個與 **require** 密切相關的宏,允許您在當前上下文中使用模組。use 宏經常被開發人員用來將外部功能引入當前詞法作用域,通常是模組。讓我們透過一個例子來理解 use 指令:
defmodule Example do use Feature, option: :value end
Use 是一個將上述內容轉換為以下內容的宏:
defmodule Example do require Feature Feature.__using__(option: :value) end
**use Module** 首先需要該模組,然後在 Module 上呼叫 **__using__** 宏。Elixir 具有強大的超程式設計功能,它具有在編譯時生成程式碼的宏。在上述例項中呼叫了 __using__ 宏,並將程式碼注入到我們的本地上下文中。本地上下文是在編譯時呼叫use 宏的地方。