Erlang 中的 ETS 声明
以下代码给了我一个错误:“之前的语法错误: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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能像在模块中那样进行变量分配。 请参阅此处。
You can't do variable assignments like that in a module. See here.
不 - 与其他语言不同,没有静态初始化的概念 - Erlang 系统没有适当的时间来执行该代码段。
然而,Erlang 确实有参数化模块的概念,这可能就是您所追求的。 看看这里 http://www.lshift。 net/blog/2008/05/18/late-binding-with-erlang 这是一篇很好的文章 - 它允许您实例化绑定到给定 ets 表的 tut 模块的“实例”并保存在模块函数调用中显式传递该句柄。
或者,如果您喜欢 OTP,则可以在状态变量中传递 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: