Elixir 標(biāo)記操作符

2023-12-14 16:47 更新

變量在Elixir中可以被重新賦值:

iex> x = 1
1
iex> x = 2
2

當(dāng)你想要對(duì)變量值進(jìn)行模式匹配,而不是重新賦值時(shí),就可以使用標(biāo)記操作符:?^?

iex> x = 1
1
iex> ^x = 2
** (MatchError) no match of right hand side value: 2
iex> {y, ^x} = {2, 1}
{2, 1}
iex> y
2
iex> {y, ^x} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}

由于我們已經(jīng)將1賦值給變量x,最后一個(gè)例子也可以寫成:

iex> {y, 1} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}

在某些情況下,你并不關(guān)心模式中特定的值??梢允褂孟聞澗€將那些值捆綁起來。例如,如果我們只看重列表頭,那么可以將尾賦值給下劃線:?_?

iex> [h | _] = [1, 2, 3]
[1, 2, 3]
iex> h
1

變量的特別之處在于它永遠(yuǎn)不可以被讀取。試圖讀取它時(shí)會(huì)返回一個(gè)未指定變量的錯(cuò)誤:?_?

iex> _
** (CompileError) iex:1: unbound variable _

盡管模式匹配使我們能夠創(chuàng)建強(qiáng)大的結(jié)構(gòu)體,它的用途依舊有限。例如,你不能夠在匹配的左邊調(diào)用函數(shù):

iex> length([1, [2], 3]) = 3
** (CompileError) iex:1: illegal pattern



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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)