官术网_书友最值得收藏!

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.

In typespecs, the string type is usually represented by String.t. You can also use string but the Elixir community discourages this, with the goal of avoiding confusion with the charlist type, which represents strings in Erlang. If you use string in typespecs, the compiler will emit a warning.

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 useplease refer to the official documentation to get a full list, at

https://hexdocs.pm/elixir/typespecs.html.

主站蜘蛛池模板: 灵石县| 惠州市| 娱乐| 东海县| 夏邑县| 秭归县| 蕉岭县| 阜宁县| 禄丰县| 丰宁| 环江| 沾化县| 宕昌县| 定安县| 大名县| 马鞍山市| 高台县| 文化| 松原市| 乐业县| 静海县| 名山县| 庆城县| 胶州市| 凤台县| 龙江县| 杨浦区| 姚安县| 北碚区| 厦门市| 抚顺县| 抚顺市| 剑河县| 克什克腾旗| 安岳县| 惠东县| 银川市| 方山县| 简阳市| 锡林郭勒盟| 英吉沙县|