从Case Warning中导出变量

6

在使用erlang进行开发时,有时会使用如下的case语句:

case Status of
    1 ->
        Variable = "Something";
    2 ->
        Variable = "Something else";
    3 ->
        Variable = {"Something very different", [1,2,3]}
end

根据某些条件将一个值分配给变量。

问题在于:如果我在case语句之后使用它:

do_something(Variable),

我收到了一条编译警告:

Warning: variable 'Variable' exported from 'case'

在Erlang中,根据某些条件为变量赋值并避免此类警告的最佳实践是什么?
2个回答

14
在Erlang中惯用的方法是将Variable赋值为case的返回值,因为case是一个表达式,它从每个分支返回最后一个表达式的值。
Variable = case Status of
    1 -> "Something";
    2 -> "Something else";
    3 -> {"Something very different", [1,2,3]}
end

4

这个警告默认情况下是不会被触发的。你需要使用warn_export_vars选项来开启它。例如,将上面的代码放入foo.erl中:

$ erlc foo.erl

(没有警告)

$ erlc +warn_export_vars foo.erl
foo.erl:14: Warning: variable 'Variable' exported from 'case' (line 6)

我认为像这样设置变量本身并没有什么问题,所以我不会打开那个选项。(使用任一惯例都可以编写易于阅读或难以阅读的代码。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接