Hello World #
一、交互式Hello World #
1.1 启动IEx #
bash
iex
1.2 输出Hello World #
elixir
iex(1)> IO.puts("Hello, World!")
Hello, World!
:ok
IO.puts/1 函数返回 :ok,这是Elixir中表示成功的原子。
1.3 理解返回值 #
在Elixir中,每个表达式都有返回值:
elixir
iex(1)> result = IO.puts("Hello")
Hello
:ok
iex(2)> result
:ok
二、脚本模式 #
2.1 创建脚本文件 #
创建 hello.exs 文件:
elixir
IO.puts("Hello, World!")
2.2 运行脚本 #
bash
elixir hello.exs
输出:
text
Hello, World!
2.3 脚本模式特点 #
- 文件扩展名为
.exs - 无需编译,直接执行
- 适合简单任务和脚本
2.4 脚本示例 #
创建 math.exs:
elixir
a = 10
b = 20
sum = a + b
difference = a - b
product = a * b
quotient = a / b
IO.puts("Sum: #{sum}")
IO.puts("Difference: #{difference}")
IO.puts("Product: #{product}")
IO.puts("Quotient: #{quotient}")
运行:
bash
elixir math.exs
输出:
text
Sum: 30
Difference: -10
Product: 200
Quotient: 0.5
三、编译模式 #
3.1 创建模块文件 #
创建 hello.ex 文件:
elixir
defmodule Hello do
def world do
IO.puts("Hello, World!")
end
end
Hello.world()
3.2 编译并运行 #
bash
elixirc hello.ex
elixir -e "Hello.world()"
3.3 编译模式特点 #
- 文件扩展名为
.ex - 编译后生成
.beam文件 - 适合正式项目
3.4 在IEx中编译 #
elixir
iex(1)> c("hello.ex")
[Hello]
iex(2)> Hello.world()
Hello, World!
:ok
四、使用Mix项目 #
4.1 创建项目 #
bash
mix new hello
cd hello
4.2 项目结构 #
text
hello/
├── lib/
│ └── hello.ex
├── test/
│ ├── hello_test.exs
│ └── test_helper.exs
├── .formatter.exs
├── .gitignore
├── mix.exs
└── README.md
4.3 编辑主模块 #
编辑 lib/hello.ex:
elixir
defmodule Hello do
@moduledoc """
Documentation for `Hello`.
"""
@doc """
Hello world.
## Examples
iex> Hello.hello()
:world
"""
def hello do
:world
end
def greet(name) do
IO.puts("Hello, #{name}!")
end
end
4.4 运行项目 #
bash
iex -S mix
elixir
iex(1)> Hello.hello()
:world
iex(2)> Hello.greet("Elixir")
Hello, Elixir!
:ok
4.5 使用escript #
创建可执行脚本。
编辑 mix.exs:
elixir
defmodule Hello.MixProject do
use Mix.Project
def project do
[
app: :hello,
version: "0.1.0",
elixir: "~> 1.16",
start_permanent: Mix.env() == :prod,
deps: deps(),
escript: [main_module: Hello.CLI]
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[]
end
end
创建 lib/hello/cli.ex:
elixir
defmodule Hello.CLI do
def main(_args) do
IO.puts("Hello, World from CLI!")
end
end
构建并运行:
bash
mix escript.build
./hello
五、字符串插值 #
5.1 基本插值 #
elixir
name = "Elixir"
IO.puts("Hello, #{name}!")
5.2 表达式插值 #
elixir
a = 10
b = 20
IO.puts("Sum: #{a + b}")
5.3 多行字符串 #
elixir
message = """
Hello, World!
This is Elixir.
Welcome!
"""
IO.puts(message)
六、注释 #
6.1 单行注释 #
elixir
IO.puts("Hello")
6.2 模块文档 #
elixir
defmodule MyModule do
@moduledoc """
This is the module documentation.
It can span multiple lines.
"""
def hello do
:world
end
end
6.3 函数文档 #
elixir
defmodule Math do
@doc """
Adds two numbers together.
## Parameters
- a: The first number
- b: The second number
## Examples
iex> Math.add(1, 2)
3
"""
def add(a, b) do
a + b
end
end
七、基本输入输出 #
7.1 输出 #
elixir
IO.puts("Hello")
IO.write("No newline")
IO.inspect([1, 2, 3], label: "List")
7.2 输入 #
elixir
name = IO.gets("What is your name? ")
IO.puts("Hello, #{String.trim(name)}!")
7.3 命令行参数 #
elixir
IO.inspect(System.argv())
运行:
bash
elixir args.exs arg1 arg2 arg3
八、错误处理 #
8.1 编译错误 #
elixir
defmodule Broken do
def broken do
# 缺少end
end
错误信息:
text
** (SyntaxError) missing terminator: end (for "do" starting at line 2)
8.2 运行时错误 #
elixir
iex(1)> 1 / 0
** (ArithmeticError) bad argument in arithmetic expression
8.3 函数未找到 #
elixir
iex(1)> UnknownModule.unknown_function()
** (UndefinedFunctionError) function UnknownModule.unknown_function/0 is undefined
九、调试技巧 #
9.1 IO.inspect #
elixir
[1, 2, 3]
|> IO.inspect(label: "Before map")
|> Enum.map(&(&1 * 2))
|> IO.inspect(label: "After map")
9.2 dbg (Elixir 1.14+) #
elixir
name = "Elixir"
dbg(name)
result = Enum.map([1, 2, 3], fn x -> x * 2 end)
dbg(result)
9.3 IEx.pry #
elixir
require IEx
defmodule Debug do
def debug_example do
x = 10
IEx.pry()
x + 1
end
end
十、总结 #
本章学习了:
- 交互式编程(IEx)
- 脚本模式(.exs)
- 编译模式(.ex)
- Mix项目结构
- 字符串插值
- 文档注释
- 基本调试技巧
准备好学习Elixir语法基础了吗?让我们进入下一章。
最后更新:2026-03-27