Erlang 中的 ETS 声明

发布于 2024-07-23 08:46:27 字数 351 浏览 4 评论 0原文

以下代码给了我一个错误:“之前的语法错误:Some_ets”

-module(tut).
-export([incr/1]).

Some_ets = ets:new(?MODULE, [bag]).

incr(X) ->
    X+1.

但是我可以在函数内声明 ETS,例如:

-module(tut).
-export([incr/1]).

incr(X) ->
    Some_ets = ets:new(?MODULE, [bag]),
    X+1.

我不能在函数外部声明 ETS 吗?

The following code gives me an error: "syntax error before: Some_ets"

-module(tut).
-export([incr/1]).

Some_ets = ets:new(?MODULE, [bag]).

incr(X) ->
    X+1.

But I am able to declare the ETS within a function, like:

-module(tut).
-export([incr/1]).

incr(X) ->
    Some_ets = ets:new(?MODULE, [bag]),
    X+1.

Can't I declare a ETS outside a function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╄→承喏 2024-07-30 08:46:28

您不能像在模块中那样进行变量分配。 请参阅此处

You can't do variable assignments like that in a module. See here.

云巢 2024-07-30 08:46:27

不 - 与其他语言不同,没有静态初始化的概念 - Erlang 系统没有适当的时间来执行该代码段。

然而,Erlang 确实有参数化模块的概念,这可能就是您所追求的。 看看这里 http://www.lshift。 net/blog/2008/05/18/late-binding-with-erlang 这是一篇很好的文章 - 它允许您实例化绑定到给定 ets 表的 tut 模块的“实例”并保存在模块函数调用中显式传递该句柄。

或者,如果您喜欢 OTP,则可以在状态变量中传递 ets 表的句柄:

init(_) ->
    Some_ets = ets:new(?MODULE, [bag]),
    {ok, Some_ets}.

and then use it in your handle_call methods:

get_ets_handle() ->
    gen_server:call(?MODULE, {getETSHandle}, infinity).

handle_call({getETSHandle}, _From, Some_ets) ->
    {reply, Some_ets, Some_ets}.

No - unlike other languages there isn't a concept of static initialization - there's no appropriate time for an Erlang system to execute that piece of code.

Erlang does have the concept of a parameterized module however, and that may be what you're after. Have a look here http://www.lshift.net/blog/2008/05/18/late-binding-with-erlang which is a good write up of that - it would allow you to instantiate an "instance" of your tut module bound to a given ets table and save passing around that handle explicitly in your module function calls.

Or if you are into OTP you could have the handle to the ets table passed around in the state variable:

init(_) ->
    Some_ets = ets:new(?MODULE, [bag]),
    {ok, Some_ets}.

and then use it in your handle_call methods:

get_ets_handle() ->
    gen_server:call(?MODULE, {getETSHandle}, infinity).

handle_call({getETSHandle}, _From, Some_ets) ->
    {reply, Some_ets, Some_ets}.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文