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

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.

主站蜘蛛池模板: 秦皇岛市| 社旗县| 乌鲁木齐市| 祁连县| 建水县| 永修县| 盖州市| 蒙自县| 顺平县| 裕民县| 南昌县| 裕民县| 大同市| 固镇县| 合川市| 台东市| 马尔康县| 营口市| 贵阳市| 石河子市| 白朗县| 水城县| 京山县| 肥东县| 扬中市| 延寿县| 平利县| 当涂县| 大宁县| 陇西县| 定边县| 屯留县| 泰来县| 利川市| 松桃| 古田县| 洮南市| 长顺县| 湖南省| 和硕县| 西宁市|