Elixir 變量域

2023-12-16 20:47 更新
要牢記try/catch/rescue/after塊中的變量定義不會泄露到外部內(nèi)容中.這是因為try塊可能會失敗,因此這些變量可能永遠不會被綁定在第一位.換句話說,這個代碼是非法的:
ex> try do
...>   raise "fail"
...>   what_happened = :did_not_raise
...> rescue
...>   _ -> what_happened = :rescued
...> end
iex> what_happened
** (RuntimeError) undefined function: what_happened/0

作為替代,你可以存儲?try?表達式的值:

iex> what_happened =
...>   try do
...>     raise "fail"
...>     :did_not_raise
...>   rescue
...>     _ -> :rescued
...>   end
iex> what_happened
:rescued

try,catchrescue的介紹到此結(jié)束.你會發(fā)現(xiàn)相較于其他語言,在Elixir中較少用到它們,盡管在某些庫或特定的代碼沒有"按照規(guī)則"書寫時,它們很有用.


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號