C 语言是现代计算机科学的基石,UNIX 操作系统、Linux 内核、众多编译器和数据库均用 C 编写。2025 年 1 月 TIOBE 指数中 C 以 10.03% 排名第 2。
1.2 核心特性
过程式编程:程序由函数组成,顺序执行
指针机制:直接访问内存地址,控制硬件
手动内存管理 :malloc / free 分配与释放堆内存
静态类型:所有变量在编译期确定类型
可移植性:符合标准的 C 程序可在任意平台编译运行
编译型语言:源码编译为机器码,执行效率极高
1.3 基础语法
Hello World
c复制代码
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
数据类型
c复制代码
// 基本类型
int a = 42; // 整数(通常 4 字节)
long b = 123456789L; // 长整数
float c = 3.14f; // 单精度浮点
double d = 3.14159265; // 双精度浮点
char e = 'A'; // 字符(1 字节)
_Bool f = 1; // 布尔(C99)
// C23 新增
nullptr_t ptr = nullptr; // 空指针类型
_BitInt(128) big = 12345678901234; // 任意宽度整数
控制流
c复制代码
// if-else
if (x > 0) {
printf("正数\n");
} else if (x < 0) {
printf("负数\n");
} else {
printf("零\n");
}
// for 循环
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
// while 循环
while (condition) { /* ... */ }
// switch
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
default: printf("Other");
}
函数
c复制代码
// 函数声明(原型)
int add(int a, int b);
// 函数定义
int add(int a, int b) {
return a + b;
}
// 递归函数
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
指针
c复制代码
int x = 10;
int *p = &x; // p 存储 x 的地址
printf("%d\n", *p); // 解引用:输出 10
*p = 20; // 通过指针修改 x 的值
// 指针算术
int arr[] = {1, 2, 3, 4, 5};
int *q = arr;
printf("%d\n", *(q + 2)); // 输出 3
// 动态内存
int *buf = malloc(10 * sizeof(int));
if (buf == NULL) { /* 处理分配失败 */ }
// 使用 buf ...
free(buf); // 必须手动释放
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap()); // 10
}
Async/Await
rust复制代码
use tokio;
#[tokio::main]
async fn main() {
let result = fetch_data("https://api.example.com").await;
println!("{:?}", result);
}
async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
let body = reqwest::get(url).await?.text().await?;
Ok(body)
}
Go 以简洁性著称,是云原生时代的基础设施语言,Docker、Kubernetes、Terraform 等核心工具均用 Go 编写。
4.2 核心特性
Goroutines:轻量级并发单元(初始仅 2KB 栈)
Channels:Goroutine 间的通信机制(CSP 模型)
接口(Interface):鸭子类型,隐式实现
垃圾回收:自动内存管理
快速编译:大型项目也能秒级编译
内置工具:格式化、测试、基准测试开箱即用
无继承:通过组合代替继承
4.3 核心语法
基础语法
go复制代码
package main
import (
"fmt"
"math"
)
func main() {
// 变量声明
var x int = 10
y := 20 // 短变量声明(类型推断)
// 常量
const Pi = 3.14159
// 多重赋值
a, b := 1, 2
a, b = b, a // 交换
fmt.Println(x, y, a, b, math.Sqrt(2))
}
函数
go复制代码
// 多返回值
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
// 命名返回值
func minMax(arr []int) (min, max int) {
min, max = arr[0], arr[0]
for _, v := range arr[1:] {
if v < min { min = v }
if v > max { max = v }
}
return // 裸 return
}
// 变参函数
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// 闭包
func makeAdder(x int) func(int) int {
return func(y int) int {
return x + y
}
}
数据结构
go复制代码
// 数组(固定大小)
arr := [5]int{1, 2, 3, 4, 5}
// Slice(动态数组)
s := []int{1, 2, 3}
s = append(s, 4, 5)
s2 := s[1:3] // 切片 [2, 3]
// Map
m := map[string]int{
"alice": 90,
"bob": 85,
}
m["charlie"] = 95
val, ok := m["alice"] // ok 判断键是否存在
// Struct
type Point struct {
X, Y float64
}
p := Point{X: 1.0, Y: 2.0}
fmt.Printf("(%f, %f)\n", p.X, p.Y)
package main
import (
"fmt"
"sync"
"time"
)
// 基本 Goroutine
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
// Channel 通信
func producer(ch chan<- int) {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}
func main() {
// WaitGroup
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
// Channel
ch := make(chan int, 10)
go producer(ch)
for val := range ch {
fmt.Println(val)
}
// Select(多路复用)
ch1 := make(chan string)
ch2 := make(chan string)
go func() { time.Sleep(1*time.Second); ch1 <- "one" }()
go func() { time.Sleep(2*time.Second); ch2 <- "two" }()
select {
case msg1 := <-ch1:
fmt.Println("Received", msg1)
case msg2 := <-ch2:
fmt.Println("Received", msg2)
case <-time.After(3 * time.Second):
fmt.Println("Timeout")
}
}
错误处理
go复制代码
import "errors"
// 自定义错误类型
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation error: %s - %s", e.Field, e.Message)
}
// errors.Is / errors.As(Go 1.13+)
var ErrNotFound = errors.New("not found")
func findUser(id int) (*User, error) {
if id <= 0 {
return nil, fmt.Errorf("invalid id %d: %w", id, ErrNotFound)
}
return &User{ID: id}, nil
}
泛型(Go 1.18+)
go复制代码
// 泛型函数
func Map[T, U any](slice []T, f func(T) U) []U {
result := make([]U, len(slice))
for i, v := range slice {
result[i] = f(v)
}
return result
}
// 类型约束
type Number interface {
~int | ~int32 | ~int64 | ~float32 | ~float64
}
func Sum[T Number](nums []T) T {
var total T
for _, n := range nums {
total += n
}
return total
}
"Write Once, Run Anywhere"(一次编写,处处运行)------Java 是企业级开发最广泛使用的语言之一,Android 平台的传统主力语言。
5.2 核心特性
JVM:字节码跨平台运行
垃圾回收(GC):自动内存管理
强面向对象:一切皆对象(基本类型除外)
泛型(Java 5+):类型安全的容器
Lambda 表达式(Java 8+):函数式编程支持
Stream API(Java 8+):声明式集合操作
Records(Java 16+):不可变数据类
Sealed Classes(Java 17+):受限继承
虚拟线程(Java 21+):轻量级线程(Project Loom)
Pattern Matching(Java 21+):模式匹配
5.3 核心语法
类与面向对象
java复制代码
// 抽象类
abstract class Vehicle {
protected String brand;
protected int year;
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
public abstract double fuelEfficiency();
@Override
public String toString() {
return brand + " (" + year + ")";
}
}
// 接口
interface Electric {
int getBatteryCapacity();
default String chargeType() { return "Type-C"; }
}
// 继承 + 接口实现
public class ElectricCar extends Vehicle implements Electric {
private int batteryKwh;
private int rangeKm;
public ElectricCar(String brand, int year, int batteryKwh, int rangeKm) {
super(brand, year);
this.batteryKwh = batteryKwh;
this.rangeKm = rangeKm;
}
@Override
public double fuelEfficiency() {
return (double) rangeKm / batteryKwh; // km/kWh
}
@Override
public int getBatteryCapacity() {
return batteryKwh;
}
}
泛型
java复制代码
// 泛型类
public class Pair<A, B> {
private A first;
private B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() { return first; }
public B getSecond() { return second; }
}
// 泛型方法
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
// 通配符
public static double sumOfList(List<? extends Number> list) {
return list.stream().mapToDouble(Number::doubleValue).sum();
}
// 不可变数据类(自动生成构造函数、getter、equals、hashCode、toString)
public record Point(double x, double y) {
// 紧凑构造函数(验证)
public Point {
if (Double.isNaN(x) || Double.isNaN(y))
throw new IllegalArgumentException("Coordinates cannot be NaN");
}
// 自定义方法
public double distanceTo(Point other) {
return Math.sqrt(Math.pow(x - other.x, 2) + Math.pow(y - other.y, 2));
}
}
var p1 = new Point(0, 0);
var p2 = new Point(3, 4);
System.out.println(p1.distanceTo(p2)); // 5.0
C# 是 .NET 生态的核心语言,广泛用于 Windows 应用、游戏开发(Unity)、企业后端和云服务(Azure)。
7.2 核心语法
csharp复制代码
// 记录类型(Record)
public record Person(string Name, int Age);
// 模式匹配
string Classify(object obj) => obj switch {
int n when n < 0 => "negative",
int n when n == 0 => "zero",
int n => "positive",
string s => $"string of length {s.Length}",
_ => "unknown"
};
// LINQ(Language Integrated Query)
using System.Linq;
var numbers = Enumerable.Range(1, 100);
var result = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.Take(10)
.ToList();
// async/await
public async Task<string> FetchDataAsync(string url) {
using var client = new HttpClient();
var response = await client.GetStringAsync(url);
return response;
}
// Nullable 引用类型(C# 8+)
string? nullableName = null;
string nonNullName = "Alice";
// 记录类型
var p1 = new Person("Alice", 30);
var p2 = p1 with { Age = 31 }; // 非破坏性更新
// 顶层语句(C# 9+)
// 无需 class Program 和 Main 方法,直接写代码
// 范围和索引(C# 8+)
int[] arr = { 1, 2, 3, 4, 5 };
var last = arr[^1]; // 5(从末尾索引)
var slice = arr[1..4]; // {2, 3, 4}
// 接口默认实现(C# 8+)
interface ILogger {
void Log(string message);
void LogError(string error) => Log($"ERROR: {error}");
}
# 基础类型与变量
name: str = "Alice"
age: int = 30
height: float = 1.65
is_student: bool = False
# 字符串格式化
msg = f"Name: {name}, Age: {age}" # f-string(推荐)
# 列表推导式
squares = [x**2 for x in range(1, 11)]
evens = [x for x in range(20) if x % 2 == 0]
# 字典推导式
word_len = {word: len(word) for word in ["hello", "world", "python"]}
# 解包
a, *b, c = [1, 2, 3, 4, 5] # a=1, b=[2,3,4], c=5
# 函数
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
# 装饰器
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} took {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(0.1)
面向对象
python复制代码
from dataclasses import dataclass, field
from typing import ClassVar
from abc import ABC, abstractmethod
@dataclass
class Animal(ABC):
name: str
age: int
count: ClassVar[int] = 0 # 类变量
def __post_init__(self):
Animal.count += 1
@abstractmethod
def speak(self) -> str:
pass
def __repr__(self):
return f"{self.__class__.__name__}(name={self.name!r}, age={self.age})"
@dataclass
class Dog(Animal):
breed: str = "Mixed"
tricks: list[str] = field(default_factory=list)
def speak(self) -> str:
return f"{self.name} says: Woof!"
def learn_trick(self, trick: str) -> None:
self.tricks.append(trick)
# 使用
dog = Dog("Rex", 3, "Labrador")
dog.learn_trick("sit")
print(dog.speak())
print(repr(dog))
生成器与迭代器
python复制代码
# 生成器函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 生成器表达式(惰性求值)
gen = (x**2 for x in range(1000000)) # 不立即计算
# 自定义迭代器
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
val = self.current
self.current += 1
return val
异步编程
python复制代码
import asyncio
import aiohttp
async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://httpbin.org/get",
"https://httpbin.org/ip",
"https://httpbin.org/headers",
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
for url, result in zip(urls, results):
print(f"{url}: {len(result)} chars")
asyncio.run(main())
module Greetable
def greet
"Hello, I'm #{name}"
end
end
module Farewell
def bye
"Goodbye from #{name}"
end
end
class Person
include Greetable
include Farewell
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def <=>(other) # 比较方法(用于排序)
@age <=> other.age
end
def to_s
"#{@name} (#{@age})"
end
end
alice = Person.new("Alice", 30)
puts alice.greet # Hello, I'm Alice
# 元编程
class String
def palindrome?
self == self.reverse
end
end
puts "racecar".palindrome? # true
# method_missing
class DynamicProxy
def initialize(target)
@target = target
end
def method_missing(method_name, *args, &block)
if @target.respond_to?(method_name)
puts "Calling #{method_name}"
@target.send(method_name, *args, &block)
else
super
end
end
end
Ruby on Rails 简例
ruby复制代码
# app/models/user.rb
class User < ApplicationRecord
has_many :posts, dependent: :destroy
has_secure_password
validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP }
validates :username, length: { minimum: 3, maximum: 50 }
scope :active, -> { where(active: true) }
scope :recent, -> { order(created_at: :desc).limit(10) }
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:show]
def index
@users = User.active.recent
render json: @users
end
def create
@user = User.new(user_params)
if @user.save
render json: @user, status: :created
else
render json: @user.errors, status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:email, :username, :password)
end
end
Julia 的目标:"像 Python 一样易写,像 C 一样快"。通过 LLVM JIT 编译实现接近 C 的性能,专为科学计算和数值分析设计。
16.2 核心语法
julia复制代码
# 基础语法
x = 42
y = 3.14
name = "Julia"
flag = true
# 类型注解(可选,用于性能优化)
function add(a::Int64, b::Int64)::Int64
a + b
end
# 多重分派(Julia 的核心特性)
function area(r::Float64)
π * r^2
end
function area(w::Float64, h::Float64)
w * h
end
println(area(3.0)) # 圆形面积
println(area(4.0, 5.0)) # 矩形面积
# 向量化操作(点运算符)
v = [1, 2, 3, 4, 5]
v .* 2 # 每个元素乘以 2
sin.(v) # 对每个元素求 sin
# 矩阵运算
A = [1 2; 3 4]
B = [5 6; 7 8]
C = A * B # 矩阵乘法
D = A .* B # 逐元素乘法
inv(A) # 逆矩阵
eigen(A) # 特征值
# 宏(元编程)
@time sum(1:1_000_000)
@benchmark sin.(rand(1000))
# 并行计算
using Distributed
@distributed for i = 1:1000
# 并行执行
end
# 类型系统
abstract type Shape end
struct Circle <: Shape
radius::Float64
end
struct Rectangle <: Shape
width::Float64
height::Float64
end
area(c::Circle) = π * c.radius^2
area(r::Rectangle) = r.width * r.height
shapes = [Circle(3.0), Rectangle(4.0, 5.0), Circle(1.5)]
total_area = sum(area.(shapes))
-- 变量(默认全局)
local name = "Alice" -- local 关键字限制作用域
local age = 30
local pi = 3.14159
-- 数据类型:nil, boolean, number, string, function, table, thread, userdata
-- 字符串
local s = "Hello, " .. name -- 连接运算符 ..
print(string.len(s))
print(string.upper(s))
print(string.format("Name: %s, Age: %d", name, age))
-- 表(Table,Lua 唯一的复合数据结构)
-- 作为数组
local arr = {10, 20, 30, 40, 50}
print(arr[1]) -- Lua 索引从 1 开始!
-- 作为字典
local person = {
name = "Bob",
age = 25,
["city"] = "Tokyo"
}
print(person.name)
print(person["age"])
-- 函数
local function factorial(n)
if n <= 1 then return 1 end
return n * factorial(n - 1)
end
-- 多返回值
local function minmax(a, b)
if a < b then return a, b
else return b, a
end
end
local min_val, max_val = minmax(10, 5)
-- 闭包
local function counter(start)
local count = start or 0
return function()
count = count + 1
return count
end
end
local c = counter(0)
print(c(), c(), c()) -- 1, 2, 3
-- OOP 通过 metatables
local Animal = {}
Animal.__index = Animal
function Animal.new(name, sound)
local self = setmetatable({}, Animal)
self.name = name
self.sound = sound
return self
end
function Animal:speak()
print(self.name .. " says: " .. self.sound)
end
local dog = Animal.new("Rex", "Woof")
dog:speak() -- Rex says: Woof
-- 迭代
for i = 1, 10 do print(i) end -- 数值 for
for k, v in pairs(person) do -- 通用 for(字典)
print(k, v)
end
for i, v in ipairs(arr) do -- 通用 for(数组)
print(i, v)
end
-- 协程
local co = coroutine.create(function(a, b)
print("Start", a, b)
local c = coroutine.yield(a + b)
print("Resumed with", c)
return "done"
end)
local ok, val = coroutine.resume(co, 10, 20) -- Start 10 20
print("Yielded:", val) -- Yielded: 30
coroutine.resume(co, "hello") -- Resumed with hello
-- Hello World
main :: IO ()
main = putStrLn "Hello, World!"
-- 基本类型
x :: Int
x = 42
y :: Double
y = 3.14
name :: String
name = "Alice"
flag :: Bool
flag = True
-- 函数定义(模式匹配)
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
-- 列表
nums :: [Int]
nums = [1, 2, 3, 4, 5]
-- 列表推导式
squares = [x^2 | x <- [1..10], odd x] -- 奇数的平方
-- 无限列表(惰性求值)
naturals = [1..]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
first10Fibs = take 10 fibs -- [0,1,1,2,3,5,8,13,21,34]
-- 高阶函数
doubled = map (*2) [1..5]
evens = filter even [1..10]
total = foldl (+) 0 [1..100]
-- 函数组合
import Data.Char (toUpper)
processStr = filter (/= ' ') . map toUpper . reverse
result = processStr "hello world" -- "DLROWOLLEH"
-- 数据类型
data Shape
= Circle Double
| Rectangle Double Double
| Triangle Double Double Double
deriving (Show, Eq)
area :: Shape -> Double
area (Circle r) = pi * r^2
area (Rectangle w h) = w * h
area (Triangle a b c) = let s = (a + b + c) / 2
in sqrt (s * (s-a) * (s-b) * (s-c))
-- Maybe(无 null)
safeDivide :: Double -> Double -> Maybe Double
safeDivide _ 0 = Nothing
safeDivide a b = Just (a / b)
-- do 记法(Monad)
compute :: Maybe Double
compute = do
x <- safeDivide 10 2
y <- safeDivide x 0 -- 这里返回 Nothing
return (x + y) -- 不会执行到这里
-- IO Monad
greetUser :: IO ()
greetUser = do
putStrLn "What is your name?"
name <- getLine
putStrLn $ "Hello, " ++ name ++ "!"
-- 类型类(Typeclass)
class Describable a where
describe :: a -> String
instance Describable Shape where
describe (Circle r) = "Circle with radius " ++ show r
describe (Rectangle w h) = "Rectangle " ++ show w ++ "x" ++ show h
describe (Triangle a b c) = "Triangle with sides " ++ show a
-- Record 语法
data Person = Person
{ personName :: String
, personAge :: Int
, personEmail :: String
} deriving (Show, Eq)
alice :: Person
alice = Person { personName = "Alice", personAge = 30, personEmail = "alice@example.com" }
-- 更新 record
olderAlice = alice { personAge = 31 }
-- Either(错误处理)
parseAge :: String -> Either String Int
parseAge s = case reads s of
[(n, "")] | n >= 0 -> Right n
_ -> Left $ "Invalid age: " ++ s
Elixir 继承 Erlang BEAM 的并发与容错优势,同时提供 Ruby 风格的优雅语法,Phoenix 框架使其成为高并发 Web 应用的热门选择。
22.2 核心语法
elixir复制代码
# 基本类型
x = 42
name = "Alice"
atom = :hello # 原子(Atom)
list = [1, 2, 3]
tuple = {1, "two", :three}
map = %{name: "Alice", age: 30}
# 模式匹配(Elixir 的核心)
{a, b, c} = {1, 2, 3}
[head | tail] = [1, 2, 3, 4, 5]
%{name: name} = %{name: "Alice", age: 30}
# 函数
defmodule Calculator do
def add(a, b), do: a + b
def factorial(0), do: 1
def factorial(n) when n > 0, do: n * factorial(n - 1)
# 管道操作符
def process(numbers) do
numbers
|> Enum.filter(&(rem(&1, 2) == 0))
|> Enum.map(&(&1 * &1))
|> Enum.sum()
end
end
# 列表操作(Enum 模块)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = numbers
|> Enum.filter(&Integer.is_even/1) # 过滤偶数
|> Enum.map(& &1 * 2) # 翻倍
|> Enum.reduce(0, &+/2) # 求和
# Stream(惰性求值)
1..1_000_000
|> Stream.filter(&(rem(&1, 2) == 0))
|> Stream.map(& &1 * &1)
|> Stream.take(5)
|> Enum.to_list()
# 进程与消息传递
pid = spawn(fn ->
receive do
{:hello, from} ->
send(from, {:world, self()})
end
end)
send(pid, {:hello, self()})
receive do
{:world, _} -> IO.puts("Got world!")
end
# GenServer(OTP 行为)
defmodule Counter do
use GenServer
def start_link(initial \\ 0) do
GenServer.start_link(__MODULE__, initial, name: __MODULE__)
end
def increment, do: GenServer.cast(__MODULE__, :increment)
def get_count, do: GenServer.call(__MODULE__, :get)
@impl true
def init(state), do: {:ok, state}
@impl true
def handle_cast(:increment, count), do: {:noreply, count + 1}
@impl true
def handle_call(:get, _from, count), do: {:reply, count, count}
end
# 用法
Counter.start_link(0)
Counter.increment()
Counter.increment()
IO.puts(Counter.get_count()) # 2
# Task(异步)
tasks = Enum.map(1..5, fn i ->
Task.async(fn ->
Process.sleep(100)
i * i
end)
end)
results = Task.await_many(tasks) # [1, 4, 9, 16, 25]
# with 语句(错误处理链)
def create_user(params) do
with {:ok, name} <- validate_name(params[:name]),
{:ok, email} <- validate_email(params[:email]),
{:ok, user} <- save_user(name, email) do
{:ok, user}
else
{:error, reason} -> {:error, reason}
end
end
Phoenix Framework 示例
elixir复制代码
# lib/my_app_web/controllers/user_controller.ex
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
alias MyApp.Accounts
def index(conn, _params) do
users = Accounts.list_users()
render(conn, :index, users: users)
end
def create(conn, %{"user" => user_params}) do
case Accounts.create_user(user_params) do
{:ok, user} ->
conn
|> put_status(:created)
|> render(:show, user: user)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(:error, changeset: changeset)
end
end
end