【发布时间】:2021-09-13 21:33:21
【问题描述】:
一、计数器功能:
在 C++ 中,我可以执行以下操作来跨函数调用缓存一个值(无耻地从 TutorialsPoint.com 复制):
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
二、数据库缓存示例:
defmodule ElixirTesting do
def test_static_function_variable do
IO.puts(get_value_from_db_cache("A"))
IO.puts(get_value_from_db_cache("B"))
IO.puts(get_value_from_db_cache("A"))
true
end
defp get_value_from_db_cache(key) do
# We want this to be static.
data_cache = %{}
if !Map.has_key?(data_cache, key) do
# Scope of this assignment is limited to local if block so does not re-bind static variable.
data_cache = Map.put_new(data_cache, key, get_value_directly_from_db(key))
end
data_cache[key]
end
@db_data %{ "A" => 3, "B" => 4, "C" => 5, "D" => 6 }
defp get_value_directly_from_db(key) do
IO.puts("Inside get_value_directly_from_db for key #{key}")
@db_data[key]
end
end
控制台输出:
Inside get_value_directly_from_db for key A
Inside get_value_directly_from_db for key B
Inside get_value_directly_from_db for key A
对于这两种情况,我如何在 Elixir 中实现相同的效果?或者,我应该如何进行重构以使用适当的功能设计来完成结果?
【问题讨论】:
标签: elixir