<27>erlang record

平时总是忘记record的某些使用方法,每次使用都要翻文档, 感觉翻博客更快,所以把record使用记录下来,
例子通过ets来使用record,结合了基本的record使用方法,例子可以直接运行
1. 定义
2. 创建
3. 访问
4. 更新
5. 做guard语句
6. record的内部替代方式
7. 还可以通过统一的赋值方式,一次给多个赋值
-module(ets_test).
-compile(export_all).
-record(student, {id,name, class}).

init(Flag) ->
ets:new(?MODULE, [set, named_table, {keypos,#student.id}, public,  {write_concurrency,Flag}]).
insert(N) ->
insert1(N).
insert1(0) ->
ok;

%%  Creating Records
insert1(N) ->
R = #student{id=N,name="test"++integer_to_list(N), class=100+N},
ets:insert(?MODULE, R),
insert1(N-1).


%%  Accessing Record Fields
lookupby_id1(N) ->
case ets:lookup(?MODULE, N) of
[] ->
not_found;
[S] ->
#student{id=Id,name=Name,class=Class} = S,
{Id,Name,Class}
end.
lookupby_id2(N) ->
case ets:lookup(?MODULE, N) of
[] ->
not_found;
[S] ->
S
end.

%%  Accessing Record Fields
lookupby_id3(N) ->
case ets:lookup(?MODULE, N) of
[] ->
not_found;
[#student{id=Id}=S] ->
Id
end.
%%  Accessing Record Fields
lookupby_id4(N) ->
AllS = ets:match(?MODULE, '$1'),
AllS2=lists:append(AllS),
lists:keysearch(N,#student.id,AllS2).

lookupby_id5(Name) ->
AllS = ets:match(?MODULE, '$1'),
AllS2=lists:append(AllS),
lists:keysearch(Name,#student.name,AllS2).

lookupby_id41(N) ->
case ets:lookup(?MODULE, N) of
[] ->
not_found;
[R] ->
R#student.id
end.

%% Updating Records
update(N) ->
case ets:lookup(?MODULE, N) of
[] ->
not_found;
[S] ->
R=S#student{name="sssssssss"},
ets:insert(?MODULE, S)
end.

%% Records in Guards

lookup6(N) ->
case ets:lookup6(?MODULE, N) of
[] ->
not_found;
[R] when R==#student{id=2,name="test2",class=102} ->
R;
_ ->
not_this_record
end.

test7() ->
record_info(fields, student).

test8() ->
record_info(size, student).

%% result is "true"
test9() ->
case ets:lookup(?MODULE, 10) of
[] ->
not_found;
[S] ->
io:format("S=~p~n",[S]),
S == {student, 10,"test10", 110}
end.

你可能感兴趣的:(erlang)