2012-03-31 38 views
2

的handle_call功能gen_server是:如果handle_call函數中存在「record = State」,會發生什麼情況?

Module:handle_call(Request, From, State) -> Result 

但我遇到一個handle_call功能是這樣的:

handle_call(info, _From, #yuv{decoder = undefined} = State) -> 
    {reply, [], State}; 

handle_call(info, _From, #yuv{decoder = Decoder} = State) -> 
    {reply, av_decoder:info(Decoder), State}; 

handle_call(_Request, _From, State) -> 
    {noreply, ok, State}. 

我想知道發生了什麼事?這是在我頭上

BTW:將YUV記錄是:

-record(yuv, { 
    host, 
    name, 
    media, 
    decoder, 
    consumer 
}). 

回答

6

如果我正確理解你的問題,你有什麼不明白下面的模式做:

foo(#bar{buz = Value} = Record) -> ... 

這是一種常見模式匹配整個和部分函數參數的方式。在我的例子中,變量Value將保存字段buz的值,變量Record將保存整個記錄的值。這可以應用在其他情況下,如:

foo([Head|Tail] = List) -> ... 
foo({First, Second} = Tuple) -> ... 

等等。只有在調用中出現相同的文字時,纔可以使用文字來代替變量,然後模式匹配纔會成功。

在您的例子:

handle_call(info, _From, #yuv{decoder = undefined} = State) -> 
    {reply, [], State}; 

handle_call(info, _From, #yuv{decoder = Decoder} = State) -> 
    {reply, av_decoder:info(Decoder), State}; 

handle_call(_Request, _From, State) -> 
    {noreply, ok, State}. 

第一種模式,如果decoder字段的值是undefined,然後回覆是[]匹配。第二個匹配decoder的所有其他情況,並使用該函數返回的值進行答覆。在這兩種情況下,State都不會被修改,並會「按原樣」返回到內部gen_server處理程序。

1

如果記錄YUV定義爲:

-record(yuv, { decoder, foo, bar, baz }).

形式:

handle_call(info, _From, #yuv{decoder = undefined} = State) -> {reply, [], State};

只是糖:

handle_call(info, _From, {yuv, undefined, _, _, _} = State) -> {reply, [], State};

函數頭部的匹配正是您所期望的,它只是試圖將函數頭中定義的記錄與記錄相匹配State wh

相關問題