Erlang中与单数下划线符号"_"匹配的模式的含义

kkbh8khc  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(141)

I'm learning Erlang and in Erlang/OTP codebase, Cowboy and others I frequently stumble at lines like this:

_ = ets:new(ac_tab, [set, public, named_table, {read_concurrency,true}]).

Like this:

_ = erlang:cancel_timer(TimerRef).

or even like this:

_ = case Version of
    'HTTP/1.1' ->
        Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1',
            headers_to_list(Headers)));
    %% Do not send informational responses to HTTP/1.0 clients. (RFC7231 6.2)
    'HTTP/1.0' ->
        ok
end.

I easily can see the reason behind pattern matches like this:

ok = some_mod:some_func().

or like this:

{ok, _} = some_mod:some_func().

This way we check that some function returned a value that fits a pattern, atom ok in first case or tuple {ok, _} where _ means something we don't care about in the second one.
As for a singular _ symbol I'm in doubt as to what this means. It looks like we just could write the expression on the right side of the = sign itself, for the examples above it would look like this:

ets:new(ac_tab, [set, public, named_table, {read_concurrency,true}]).

erlang:cancel_timer(TimerRef).

case Version of
    'HTTP/1.1' ->
        Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1',
            headers_to_list(Headers)));
    %% Do not send informational responses to HTTP/1.0 clients. (RFC7231 6.2)
    'HTTP/1.0' ->
        ok
end.

and nothing would have changed.

yiytaume

yiytaume1#

_匹配用于取消对不匹配返回的dialyzer警告。

kwvwclae

kwvwclae2#

_匿名变量,请参阅变量。它的行为类似于变量,但其值被忽略。
如果它位于赋值语句的左手,则可以省略,但你经常会在更复杂的结构中发现它:

{key, Value, _} = some_function(),

你只对值的某些部分感兴趣。

相关问题