- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 376字
- 2021-08-05 10:42:50
Typespecs
Typespecs are written using the @spec module directive, followed by function_name(argument_type) :: return_type. This module directive is placed right before the definition of the function we're annotating.
To demonstrate how to apply typespecs to a function, let's bring back our palindrome? function:
$ cat examples/string_helper.ex
defmodule StringHelper do
def palindrome?(term) do
String.reverse(term) == term
end
end
Given that the module name is StringHelper, and that it's using functions from the String module, we can see that this function receives a string. As it uses the == operator, and also hinted at by the trailing ? on the function name, we know this function returns a Boolean. With this information, writing the typespec for this function is straightforward:
$ cat examples/string_helper_palindrome_with_typespec.ex
defmodule StringHelper do
@spec palindrome?(String.t) :: boolean
def palindrome?(term) do
String.reverse(term) == term
end
end
You can also define your own types to use in typespecs, by using the @type directive within a module (usually the module where that type is used the most). Let's say that you frequently use a tuple in your module that contains the name of a country on the first element, and its population on the second, as in {"Portugal, 10_309_573}. You can create a type for this data structure with this:
@type country_with_population :: {String.t, integer}
Then, you could use country_with_population in typespecs as you'd use any other type.
Defining a type in a module will export it, making it available to all modules. If you want your type to be private to the module where it's defined, use the @typep directive. Similar to the @moduledoc and @doc directives (to document modules and functions, respectively), you can use the @typedoc directive to provide documentation for a certain type.
Typespecs also provide great documentation, as we can quickly grasp what types this function accepts and returns. This example only shows a subset of the types you can use–please refer to the official documentation to get a full list, at
- TypeScript入門與實戰
- ASP.NET Core 2 and Vue.js
- OpenNI Cookbook
- Hands-On C++ Game Animation Programming
- Spring Boot企業級項目開發實戰
- Learning Hunk
- 批調度與網絡問題的組合算法
- 代替VBA!用Python輕松實現Excel編程
- Visual FoxPro 6.0程序設計
- PrimeFaces Blueprints
- C++程序設計教程
- Getting Started with Windows Server Security
- Java核心技術速學版(第3版)
- Laravel 5.x Cookbook
- R語言編程基礎