- 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
- 程序員修煉之道:程序設(shè)計入門30講
- DevOps with Kubernetes
- Python從菜鳥到高手(第2版)
- jQuery從入門到精通 (軟件開發(fā)視頻大講堂)
- Visual C#.NET程序設(shè)計
- Mathematica Data Analysis
- .NET 3.5編程
- Regression Analysis with Python
- 零基礎(chǔ)學(xué)HTML+CSS第2版
- Data Science Algorithms in a Week
- 征服C指針(第2版)
- 實驗編程:PsychoPy從入門到精通
- FusionCharts Beginner’s Guide:The Official Guide for FusionCharts Suite
- C語言從入門到精通(視頻實戰(zhàn)版)
- 走近SDN/NFV