📜  instance var elixir (1)

📅  最后修改于: 2023-12-03 15:15:50.780000             🧑  作者: Mango

Instance Variable in Elixir

In Elixir, instance variables are used to store data that belongs to a specific instance of a module. They are defined using the @ symbol followed by the variable name.

Defining and Accessing Instance Variables

To define an instance variable, we use the @ symbol followed by the variable name. For example, let's define an instance variable called message:

defmodule Greeting do
  @message "Hello World"

  def say_greeting do
    IO.puts @message
  end
end

In the above example, we define a module called Greeting with an instance variable message that contains the string "Hello World".

To access the message instance variable from the say_greeting function, we use the @ symbol followed by the variable name:

defmodule Greeting do
  @message "Hello World"

  def say_greeting do
    IO.puts @message
  end
end

Greeting.say_greeting # output: Hello World
Visibility of Instance Variables

Instance variables are not visible outside of the module in which they are defined. This means that they cannot be accessed from other modules or functions unless they are defined within a public function.

defmodule Greeting do
  @message "Hello World"

  defp internal_func do
    IO.puts @message
  end

  def public_func do
    internal_func
  end
end

In the above example, we define an instance variable called message and two functions, internal_func and public_func. The internal_func function has access to the @message instance variable, but it is defined as private using the defp keyword. The public_func function is defined as public and simply calls internal_func.

Conclusion

In Elixir, instance variables are used to store data that belongs to a specific instance of a module. They are defined using the @ symbol followed by the variable name. Instance variables are not visible outside of the module in which they are defined unless they are defined within a public function.