主流编程语言完全知识总结与使用教程
目录
- C
- C++
- Rust
- Go
- Java
- Kotlin
- C#
- Python
- JavaScript
- TypeScript
- Ruby
- PHP
- Swift
- Dart
- R
- Julia
- Lua
- Perl
- Haskell
- Scala
- Erlang
- Elixir
- Clojure
- 语言横向对比
- 选型建议
1. C
1.1 简介与历史
C 语言是现代计算机科学的基石,UNIX 操作系统、Linux 内核、众多编译器和数据库均用 C 编写。2025 年 1 月 TIOBE 指数中 C 以 10.03% 排名第 2。
1.2 核心特性
- 过程式编程:程序由函数组成,顺序执行
- 指针机制:直接访问内存地址,控制硬件
- 手动内存管理 :
malloc / free 分配与释放堆内存
- 静态类型:所有变量在编译期确定类型
- 可移植性:符合标准的 C 程序可在任意平台编译运行
- 编译型语言:源码编译为机器码,执行效率极高
1.3 基础语法
Hello World
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
数据类型
// 基本类型
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; // 任意宽度整数
控制流
// 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");
}
函数
// 函数声明(原型)
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);
}
指针
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); // 必须手动释放
结构体
typedef struct {
char name[50];
int age;
float salary;
} Employee;
Employee emp = {"Alice", 30, 8500.0f};
printf("Name: %s, Age: %d\n", emp.name, emp.age);
// 结构体指针
Employee *ep = &emp;
printf("Name: %s\n", ep->name); // 使用 -> 操作符
文件 I/O
FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
fprintf(fp, "Hello, File!\n");
fclose(fp);
}
// 读取文件
FILE *fr = fopen("data.txt", "r");
char line[256];
while (fgets(line, sizeof(line), fr)) {
printf("%s", line);
}
fclose(fr);
1.4 高级主题
预处理器
#define MAX_SIZE 100
#define SQUARE(x) ((x) * (x))
#ifdef DEBUG
printf("Debug mode\n");
#endif
#include <stdlib.h>
多线程(POSIX)
#include <pthread.h>
void *thread_func(void *arg) {
printf("Thread running\n");
return NULL;
}
int main(void) {
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
pthread_join(tid, NULL);
return 0;
}
1.5 优缺点
| 优点 |
缺点 |
| 执行效率极高,接近汇编 |
手动内存管理,易产生内存泄漏、悬挂指针 |
| 跨平台可移植 |
无内置异常处理 |
| 资源占用极低,适合嵌入式 |
约 70% 的 C/C++ 漏洞源于内存安全问题 |
| 广泛的标准库与第三方支持 |
无面向对象支持 |
| 系统级编程的事实标准 |
标准库功能有限 |
1.6 典型应用场景
- 操作系统:Linux 内核、Windows 内核
- 嵌入式系统:单片机、RTOS
- 编译器与解释器:GCC、CPython
- 数据库:SQLite、MySQL 核心
- 游戏引擎底层:Unreal Engine 部分模块
- 网络协议栈:TCP/IP 实现
1.7 工具链
| 工具 |
说明 |
| GCC |
GNU Compiler Collection,最广泛使用的开源编译器 |
| Clang |
LLVM 项目编译器,更好的错误信息 |
| CMake |
跨平台构建系统 |
| Make |
传统构建工具 |
| GDB |
GNU 调试器 |
| Valgrind |
内存泄漏检测工具 |
| Clang-Tidy |
静态分析工具 |
2. C++
2.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1983 年(Bjarne Stroustrup) |
| 范式 |
多范式:面向对象、过程式、泛型、函数式 |
| 类型系统 |
静态强类型 |
| 最新标准 |
C++23(2023),C++26 开发中 |
| 典型编译器 |
GCC、Clang、MSVC |
| 官网 |
https://isocpp.org |
C++ 在 C 的基础上添加了面向对象、泛型编程和零成本抽象,是游戏开发、高频交易和系统软件的首选语言。
2.2 核心特性
- 面向对象:封装、继承、多态
- 模板(泛型):编译期代码复用
- RAII(Resource Acquisition Is Initialization):资源自动管理
- STL:标准模板库,容器、算法、迭代器
- Move 语义:C++11 引入,避免不必要的深拷贝
- 智能指针 :
unique_ptr、shared_ptr、weak_ptr
- Lambda 表达式:匿名函数
- constexpr:编译期求值
2.3 核心语法
类与对象
#include <iostream>
#include <string>
class Animal {
protected:
std::string name;
int age;
public:
// 构造函数
Animal(const std::string& name, int age)
: name(name), age(age) {}
// 虚析构函数(多态必须)
virtual ~Animal() = default;
// 纯虚函数(抽象方法)
virtual void speak() const = 0;
// 普通成员函数
void introduce() const {
std::cout << "I am " << name << ", age " << age << "\n";
}
// Getter
const std::string& getName() const { return name; }
};
class Dog : public Animal {
public:
Dog(const std::string& name, int age) : Animal(name, age) {}
void speak() const override {
std::cout << name << " says: Woof!\n";
}
};
class Cat : public Animal {
public:
Cat(const std::string& name, int age) : Animal(name, age) {}
void speak() const override {
std::cout << name << " says: Meow!\n";
}
};
int main() {
// 多态
std::vector<std::unique_ptr<Animal>> animals;
animals.push_back(std::make_unique<Dog>("Rex", 3));
animals.push_back(std::make_unique<Cat>("Whiskers", 5));
for (const auto& a : animals) {
a->speak();
a->introduce();
}
return 0;
}
模板
// 函数模板
template<typename T>
T max_val(T a, T b) {
return (a > b) ? a : b;
}
// 类模板
template<typename T, size_t N>
class Array {
private:
T data[N];
public:
T& operator[](size_t i) { return data[i]; }
size_t size() const { return N; }
};
// 概念(C++20)
template<typename T>
concept Numeric = std::is_arithmetic_v<T>;
template<Numeric T>
T square(T x) { return x * x; }
STL 容器与算法
#include <vector>
#include <map>
#include <algorithm>
#include <numeric>
std::vector<int> nums = {5, 2, 8, 1, 9, 3};
// 排序
std::sort(nums.begin(), nums.end());
// Lambda + 算法
std::for_each(nums.begin(), nums.end(), [](int x) {
std::cout << x << " ";
});
// 查找
auto it = std::find(nums.begin(), nums.end(), 8);
// 累加
int sum = std::accumulate(nums.begin(), nums.end(), 0);
// map
std::map<std::string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 88;
for (const auto& [name, score] : scores) { // C++17 结构化绑定
std::cout << name << ": " << score << "\n";
}
智能指针与 RAII
#include <memory>
// unique_ptr:独占所有权
auto uptr = std::make_unique<int>(42);
// 离开作用域自动释放
// shared_ptr:共享所有权(引用计数)
auto sptr1 = std::make_shared<std::string>("Hello");
auto sptr2 = sptr1; // 引用计数 = 2
// weak_ptr:弱引用,打破循环引用
std::weak_ptr<std::string> wptr = sptr1;
if (auto locked = wptr.lock()) {
std::cout << *locked << "\n";
}
Move 语义
#include <utility>
std::vector<int> createVector() {
std::vector<int> v = {1, 2, 3, 4, 5};
return v; // 编译器可能应用 RVO
}
std::string s1 = "Hello, World!";
std::string s2 = std::move(s1); // 移动,s1 变为空
C++20/23 新特性
// Ranges(C++20)
#include <ranges>
auto filtered = nums | std::views::filter([](int x) { return x > 3; })
| std::views::transform([](int x) { return x * 2; });
// Coroutines(C++20)
#include <coroutine>
// 协程实现生成器...
// std::format(C++20)
#include <format>
std::string msg = std::format("Hello, {}! Age: {}", "Alice", 30);
2.4 优缺点
| 优点 |
缺点 |
| 零成本抽象、极致性能 |
学习曲线陡峭 |
| 多范式灵活编程 |
复杂的内存管理(虽有智能指针) |
| 极其庞大的生态系统 |
编译时间长 |
| 向后兼容 C |
编译错误信息复杂难读 |
| 游戏、金融、系统的工业标准 |
历史包袱重 |
2.5 典型应用场景
- 游戏引擎:Unreal Engine、Unity(底层)
- 高频交易系统
- 浏览器引擎:Chrome V8、Firefox
- 图形处理:OpenCV、OpenGL
- 嵌入式与操作系统
2.6 工具链
| 工具 |
说明 |
| CMake + Ninja |
现代主流构建系统 |
| vcpkg / Conan |
C++ 包管理器 |
| CLion / VS Code |
IDE |
| Sanitizers |
ASan、UBSan 运行时检测 |
| cppcheck |
静态分析 |
| Google Test |
单元测试框架 |
3. Rust
3.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2006 年(Graydon Hoare),2015 年发布 1.0 |
| 范式 |
系统编程、函数式、并发 |
| 类型系统 |
静态强类型、类型推断 |
| 最新版本 |
Rust 1.85(2025 年 2 月,Rust 2024 Edition) |
| 包管理 |
Cargo |
| 官网 |
https://www.rust-lang.org |
Rust 连续 9 年(2016-2024)荣登 Stack Overflow "最受喜爱编程语言"第一名,以 83% 的喜爱率。White House 网络安全办公室在 2024 年报告中推荐迁移到以 Rust 为代表的内存安全语言。
3.2 核心特性
所有权系统(Ownership)
Rust 的三大所有权规则:
- 每个值只有一个所有者(owner)
- 同一时刻只能有一个所有者
- 当所有者离开作用域,值被自动 drop
fn main() {
let s1 = String::from("hello");
let s2 = s1; // s1 的所有权移动到 s2,s1 失效
// println!("{}", s1); // 编译错误:s1 已被移动
println!("{}", s2); // OK
}
借用(Borrowing)
fn calculate_length(s: &String) -> usize { // 借用,不转移所有权
s.len()
} // s 离开作用域,但不会释放(因为只是借用)
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("'{}' has {} characters", s1, len); // s1 仍然有效
}
// 可变借用(同一时间只能有一个)
fn change(s: &mut String) {
s.push_str(", world");
}
let mut s = String::from("hello");
change(&mut s);
生命周期(Lifetimes)
// 生命周期注解确保引用有效
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let s1 = String::from("long string");
let result;
{
let s2 = String::from("xy");
result = longest(s1.as_str(), s2.as_str());
println!("The longest: {}", result);
}
}
3.3 核心语法
变量与类型
// 变量默认不可变
let x = 5;
let mut y = 10; // 可变变量
y += 1;
// 常量
const MAX_POINTS: u32 = 100_000;
// 类型推断
let guess: u32 = "42".parse().expect("Not a number");
// 元组
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (a, b, c) = tup; // 解构
// 数组
let arr = [1, 2, 3, 4, 5];
let months = ["Jan", "Feb", "Mar"]; // 长度固定
// 基本数值类型
// i8, i16, i32, i64, i128, isize(有符号)
// u8, u16, u32, u64, u128, usize(无符号)
// f32, f64(浮点)
// bool, char
结构体与枚举
// 结构体
#[derive(Debug, Clone)]
struct Rectangle {
width: f64,
height: f64,
}
impl Rectangle {
// 关联函数(类似静态方法)
fn new(width: f64, height: f64) -> Self {
Rectangle { width, height }
}
// 方法
fn area(&self) -> f64 {
self.width * self.height
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
// 枚举(代数数据类型)
#[derive(Debug)]
enum Shape {
Circle(f64), // 半径
Rectangle(f64, f64), // 宽、高
Triangle(f64, f64, f64), // 三边
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
Option 与 Result(错误处理)
// Option<T>:值可能存在或不存在(无 null)
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 { None } else { Some(a / b) }
}
let result = divide(10.0, 2.0);
match result {
Some(val) => println!("Result: {}", val),
None => println!("Cannot divide by zero"),
}
// ? 操作符简化 Option/Result 传播
fn parse_and_double(s: &str) -> Option<i32> {
let n: i32 = s.parse().ok()?;
Some(n * 2)
}
// Result<T, E>:可恢复错误处理
use std::fs::File;
use std::io::{self, Read};
fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?; // ? 自动传播错误
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
Trait(特征)
trait Greet {
fn greet(&self) -> String;
// 默认实现
fn shout(&self) -> String {
self.greet().to_uppercase()
}
}
struct English;
struct Chinese;
impl Greet for English {
fn greet(&self) -> String {
"Hello!".to_string()
}
}
impl Greet for Chinese {
fn greet(&self) -> String {
"你好!".to_string()
}
}
// 泛型 + Trait Bound
fn print_greeting<T: Greet>(item: &T) {
println!("{}", item.greet());
}
并发
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
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)
}
3.4 优缺点
| 优点 |
缺点 |
| 内存安全无需 GC |
学习曲线极陡(借用检查器) |
| 极致性能,媲美 C/C++ |
编译时间较长 |
| 无数据竞争(编译期保证) |
生态系统相对 Python/Java 还不够完善 |
| 零成本抽象 |
借用规则有时让人抓狂 |
| 优秀的工具链(Cargo) |
某些场景代码较为冗长 |
3.5 典型应用场景
- 系统编程:操作系统、驱动程序(Linux 内核 Rust 支持)
- WebAssembly:浏览器高性能模块
- 网络服务:Cloudflare、Discord 部分服务
- 嵌入式:IoT 设备
- 工具链:ripgrep、exa、fd 等命令行工具
- 区块链:Solana、Polkadot
3.6 工具链
| 工具 |
说明 |
| Cargo |
官方包管理器 + 构建工具 |
| rustup |
工具链管理器(安装、更新 Rust) |
| clippy |
Linter(代码质量检查) |
| rustfmt |
代码格式化 |
| tokio |
异步运行时 |
| serde |
序列化/反序列化框架 |
| actix-web / axum |
Web 框架 |
4. Go
4.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2009 年(Google:Robert Griesemer、Rob Pike、Ken Thompson) |
| 范式 |
过程式、并发 |
| 类型系统 |
静态强类型,类型推断 |
| 最新版本 |
Go 1.23(2024) |
| 包管理 |
Go Modules |
| 官网 |
https://go.dev |
Go 以简洁性著称,是云原生时代的基础设施语言,Docker、Kubernetes、Terraform 等核心工具均用 Go 编写。
4.2 核心特性
- Goroutines:轻量级并发单元(初始仅 2KB 栈)
- Channels:Goroutine 间的通信机制(CSP 模型)
- 接口(Interface):鸭子类型,隐式实现
- 垃圾回收:自动内存管理
- 快速编译:大型项目也能秒级编译
- 内置工具:格式化、测试、基准测试开箱即用
- 无继承:通过组合代替继承
4.3 核心语法
基础语法
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))
}
函数
// 多返回值
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
}
}
数据结构
// 数组(固定大小)
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)
接口
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
func printShape(s Shape) {
fmt.Printf("Area: %.2f, Perimeter: %.2f\n", s.Area(), s.Perimeter())
}
Goroutines 与 Channels
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")
}
}
错误处理
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+)
// 泛型函数
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
}
4.4 优缺点
| 优点 |
缺点 |
| 简洁易学,语法极简 |
错误处理繁琐(大量 if err != nil) |
| 极快的编译速度 |
泛型支持较晚(1.18 才加入) |
| 原生并发支持(Goroutines) |
无泛型前生态代码重复多 |
| 单二进制部署 |
缺少函数式编程特性 |
| 云原生生态极强 |
GC 停顿(低延迟场景有影响) |
4.5 典型应用场景
- 云基础设施:Docker、Kubernetes、Terraform、Consul
- 微服务:高并发 API 服务
- 命令行工具:Hugo、gh
- 网络编程:代理、VPN
4.6 工具链
| 工具 |
说明 |
| go build/run/test |
内置构建、运行、测试 |
| go mod |
模块管理 |
| gofmt / goimports |
代码格式化 |
| golangci-lint |
Linter 聚合工具 |
| Gin / Echo / Fiber |
Web 框架 |
| GORM |
ORM 框架 |
| prometheus-client |
监控 |
5. Java
5.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1995 年(Sun Microsystems,James Gosling) |
| 范式 |
面向对象、命令式 |
| 类型系统 |
静态强类型 |
| 最新 LTS 版本 |
Java 21(2023 年 9 月,LTS) |
| 最新版本 |
Java 23(2024) |
| 运行时 |
JVM(Java Virtual Machine) |
| 官网 |
https://www.java.com / https://openjdk.org |
"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 核心语法
类与面向对象
// 抽象类
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;
}
}
泛型
// 泛型类
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();
}
Lambda 与 Stream API
import java.util.*;
import java.util.stream.*;
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
// 过滤、映射、收集
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
// 统计
Map<Integer, List<String>> byLength = names.stream()
.collect(Collectors.groupingBy(String::length));
// reduce
int total = IntStream.rangeClosed(1, 100).sum(); // 5050
// 并行流
long count = names.parallelStream()
.filter(s -> s.startsWith("A"))
.count();
Records(Java 16+)
// 不可变数据类(自动生成构造函数、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
虚拟线程(Java 21)
// Project Loom:轻量级虚拟线程
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100));
System.out.println("Task " + i + " done");
return null;
});
});
} // executor 自动关闭,等待所有任务完成
Pattern Matching(Java 21)
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double base, double height) implements Shape {}
double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.w() * r.h();
case Triangle t -> 0.5 * t.base() * t.height();
};
}
异常处理
// try-with-resources(自动关闭资源)
try (var br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
} finally {
System.out.println("Always executed");
}
// 自定义异常
public class AppException extends RuntimeException {
private final int errorCode;
public AppException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() { return errorCode; }
}
5.4 优缺点
| 优点 |
缺点 |
| 跨平台(JVM) |
启动速度慢(传统 JVM) |
| 极其成熟的企业生态 |
内存占用较大 |
| 强大的并发库 |
语法相对啰嗦(相比 Kotlin) |
| 向后兼容性极好 |
历史包袱(旧 API 冗余) |
| 大量框架(Spring 生态) |
GC 停顿可能影响低延迟 |
5.5 典型应用场景
- 企业级后端:Spring Boot 微服务
- 大数据:Hadoop、Spark(Scala/Java)
- Android 开发(传统)
- 金融系统:银行核心系统
- 搜索引擎:Elasticsearch、Lucene
5.6 工具链
| 工具 |
说明 |
| Maven / Gradle |
构建与依赖管理 |
| Spring Boot |
最流行的企业框架 |
| IntelliJ IDEA |
最强 Java IDE |
| JUnit 5 / Mockito |
测试框架 |
| Lombok |
减少样板代码 |
| GraalVM |
原生编译(加速启动) |
6. Kotlin
6.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2011 年(JetBrains),2017 年 Google 宣布 Android 一等语言 |
| 范式 |
面向对象、函数式、多范式 |
| 类型系统 |
静态强类型、类型推断、Null 安全 |
| 最新版本 |
Kotlin 2.1(2025) |
| 目标平台 |
JVM、Android、JavaScript、Native(KMM) |
| 官网 |
https://kotlinlang.org |
6.2 核心特性
- Null 安全 :类型系统区分可空(
String?)和非空(String)
- 数据类(data class):自动生成 equals/hashCode/toString/copy
- 扩展函数:为已有类添加方法,无需继承
- 协程(Coroutines):轻量级异步编程
- Smart Cast:自动类型转换
- Sealed Class:枚举式密封类
- Multiplatform(KMP):共享业务逻辑跨 iOS/Android
6.3 核心语法
// Null 安全
val name: String = "Alice" // 非空
val nickname: String? = null // 可空
println(nickname?.length) // 安全调用:null
println(nickname ?: "N/A") // Elvis 操作符:N/A
val len = nickname!!.length // 非空断言(可能 NPE)
// 数据类
data class User(
val id: Int,
val name: String,
val email: String
)
val user = User(1, "Alice", "alice@example.com")
val updated = user.copy(email = "new@example.com") // 不可变复制
// 扩展函数
fun String.isPalindrome(): Boolean = this == this.reversed()
println("racecar".isPalindrome()) // true
// 高阶函数 + Lambda
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evens = numbers.filter { it % 2 == 0 }
val doubled = numbers.map { it * 2 }
val sum = numbers.fold(0) { acc, n -> acc + n }
// when 表达式
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
else -> "F"
}
// Sealed Class
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val message: String) : Result<Nothing>()
object Loading : Result<Nothing>()
}
// 处理 sealed class
fun handleResult(result: Result<String>) = when (result) {
is Result.Success -> println("Data: ${result.data}")
is Result.Error -> println("Error: ${result.message}")
Result.Loading -> println("Loading...")
}
协程
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
// 基本协程
fun main() = runBlocking {
val job = launch {
delay(1000L)
println("World!")
}
println("Hello,")
job.join()
}
// async/await
suspend fun fetchData(): String = withContext(Dispatchers.IO) {
// 模拟网络请求
delay(500)
"Data from server"
}
// Flow(响应式流)
fun numberFlow(): Flow<Int> = flow {
for (i in 1..10) {
delay(100)
emit(i)
}
}
fun main() = runBlocking {
numberFlow()
.filter { it % 2 == 0 }
.map { it * it }
.collect { println(it) }
}
6.4 优缺点
| 优点 |
缺点 |
| 完全兼容 Java |
编译速度比 Java 慢 |
| Null 安全减少 NPE |
学习曲线(对 Java 开发者较平缓) |
| 更简洁的语法 |
KMP 生态仍在成熟中 |
| 协程简化异步编程 |
某些高级特性过于"魔法" |
| Google 官方推荐 Android 语言 |
|
7. C#
7.1 简介与历史
C# 是 .NET 生态的核心语言,广泛用于 Windows 应用、游戏开发(Unity)、企业后端和云服务(Azure)。
7.2 核心语法
// 记录类型(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}");
}
Unity 游戏开发示例
using UnityEngine;
public class PlayerController : MonoBehaviour {
[SerializeField] private float speed = 5f;
[SerializeField] private float jumpForce = 10f;
private Rigidbody2D rb;
private bool isGrounded;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
float horizontal = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) {
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
}
7.3 优缺点
| 优点 |
缺点 |
| 微软强力支持,持续更新 |
长期与 Windows 绑定(虽已开源) |
| Unity 游戏开发首选 |
.NET 生态碎片化历史问题 |
| 强大的 LINQ 和异步支持 |
跨平台成熟度不如 Java |
| 现代语言特性丰富 |
部分高级特性学习曲线陡峭 |
8. Python
8.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1991 年(Guido van Rossum) |
| 范式 |
多范式:面向对象、函数式、过程式 |
| 类型系统 |
动态类型(可选静态类型提示) |
| 最新版本 |
Python 3.13(2024) |
| 主要实现 |
CPython(官方)、PyPy(JIT 加速)、Jython、IronPython |
| 官网 |
https://www.python.org |
Python 是 2024-2025 年 TIOBE 指数排名第一的语言,是 AI/ML 领域的事实标准。
8.2 核心语法
# 基础类型与变量
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)
面向对象
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))
生成器与迭代器
# 生成器函数
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
异步编程
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())
类型注解(Type Hints)
from typing import TypeVar, Generic, Protocol
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
def peek(self) -> T:
return self._items[-1]
def is_empty(self) -> bool:
return len(self._items) == 0
# Protocol(结构子类型,Python 3.8+)
class Drawable(Protocol):
def draw(self) -> None: ...
def render(item: Drawable) -> None:
item.draw()
常用标准库
# pathlib(文件路径)
from pathlib import Path
p = Path("data") / "file.txt"
p.write_text("Hello")
content = p.read_text()
# json
import json
data = {"name": "Alice", "scores": [95, 87, 92]}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
obj = json.loads(json_str)
# collections
from collections import Counter, defaultdict, deque
counter = Counter("abracadabra")
print(counter.most_common(3))
# itertools
from itertools import chain, combinations, product
pairs = list(combinations([1, 2, 3, 4], 2))
8.3 主要生态
| 领域 |
框架/库 |
| Web 后端 |
Django、FastAPI、Flask |
| 数据科学 |
NumPy、Pandas、Matplotlib、Seaborn |
| 机器学习 |
scikit-learn、TensorFlow、PyTorch |
| 深度学习 |
PyTorch、Keras、Jax |
| 爬虫 |
Scrapy、BeautifulSoup、Playwright |
| 测试 |
pytest、unittest |
| 异步 |
asyncio、aiohttp、httpx |
| 任务队列 |
Celery、RQ |
8.4 优缺点
| 优点 |
缺点 |
| 语法简洁,学习曲线最平缓 |
执行速度慢(GIL 限制真正并行) |
| 丰富的生态(PyPI 50万+ 包) |
动态类型易出运行时错误 |
| AI/ML 领域绝对主导 |
不适合系统级和高性能场景 |
| 交互式开发(Jupyter Notebook) |
移动端支持弱 |
| 脚本、自动化首选 |
部署比编译语言复杂 |
9. JavaScript
9.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1995 年(Brendan Eich,10 天创造) |
| 范式 |
多范式:函数式、面向对象、事件驱动 |
| 类型系统 |
动态弱类型 |
| 最新标准 |
ECMAScript 2024(ES15) |
| 运行时 |
V8(Chrome/Node.js)、SpiderMonkey(Firefox)、JavaScriptCore(Safari) |
| 官网 |
https://tc39.es(标准) / https://nodejs.org |
JavaScript 是 Stack Overflow 调查中连续 12 年最常用的语言,是唯一能在浏览器原生运行的编程语言。
9.2 核心语法
// 变量声明
const PI = 3.14159; // 常量(块级作用域)
let count = 0; // 变量(块级作用域)
// var(函数作用域,避免使用)
// 解构赋值
const [first, , third] = [1, 2, 3];
const { name, age = 18 } = { name: "Alice" };
// 扩展运算符
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 };
// 模板字符串
const greeting = `Hello, ${name}! You are ${age} years old.`;
// 可选链与空值合并
const street = user?.address?.street ?? "Unknown";
// 箭头函数
const add = (a, b) => a + b;
const double = x => x * 2;
const getObj = () => ({ key: "value" }); // 返回对象字面量
// 函数默认参数
function createUser(name, role = "user", active = true) {
return { name, role, active };
}
原型与类
// ES6 类语法
class EventEmitter {
#listeners = new Map(); // 私有字段(ES2022)
on(event, listener) {
if (!this.#listeners.has(event)) {
this.#listeners.set(event, []);
}
this.#listeners.get(event).push(listener);
return this; // 链式调用
}
emit(event, ...args) {
const listeners = this.#listeners.get(event) ?? [];
listeners.forEach(listener => listener(...args));
return this;
}
off(event, listener) {
const list = this.#listeners.get(event) ?? [];
this.#listeners.set(event, list.filter(l => l !== listener));
return this;
}
}
// 继承
class Logger extends EventEmitter {
#prefix;
constructor(prefix = '[LOG]') {
super();
this.#prefix = prefix;
}
log(message) {
const formatted = `${this.#prefix} ${message}`;
console.log(formatted);
this.emit('log', formatted);
}
}
异步编程
// Promise
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: `User ${id}` });
} else {
reject(new Error("Invalid ID"));
}
}, 100);
});
}
// async/await
async function loadUserData(userId) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(user.id);
return { user, posts };
} catch (error) {
console.error("Error:", error.message);
throw error;
}
}
// Promise.all(并发)
async function loadAll(userIds) {
const users = await Promise.all(userIds.map(id => fetchUser(id)));
return users;
}
// Promise.allSettled(容错并发)
const results = await Promise.allSettled([
fetchUser(1),
fetchUser(-1),
fetchUser(2),
]);
results.forEach(r => {
if (r.status === 'fulfilled') console.log(r.value);
else console.error(r.reason);
});
函数式编程
// 高阶函数
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);
const transform = pipe(
x => x * 2,
x => x + 1,
x => `Result: ${x}`
);
console.log(transform(5)); // "Result: 11"
// 柯里化
const curry = fn => {
const arity = fn.length;
return function curried(...args) {
if (args.length >= arity) return fn(...args);
return (...moreArgs) => curried(...args, ...moreArgs);
};
};
const add3 = curry((a, b, c) => a + b + c);
console.log(add3(1)(2)(3)); // 6
console.log(add3(1, 2)(3)); // 6
Proxy 与 Reflect
// 响应式数据
function reactive(target) {
return new Proxy(target, {
get(obj, key) {
console.log(`Getting ${key}`);
return Reflect.get(obj, key);
},
set(obj, key, value) {
console.log(`Setting ${key} = ${value}`);
return Reflect.set(obj, key, value);
}
});
}
const state = reactive({ count: 0 });
state.count++; // 触发 get 和 set
9.3 Node.js 生态
// HTTP 服务器
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello World' }));
});
server.listen(3000, () => console.log('Server on port 3000'));
// Express 框架
const express = require('express');
const app = express();
app.use(express.json());
app.get('/users/:id', async (req, res) => {
const { id } = req.params;
try {
const user = await User.findById(id);
res.json(user);
} catch (err) {
res.status(404).json({ error: 'User not found' });
}
});
9.4 优缺点
| 优点 |
缺点 |
| 唯一的浏览器原生语言 |
弱类型,运行时易出错 |
| 前后端同语言(Node.js) |
历史包袱与"设计失误"(== 等) |
| 最大的生态系统(NPM) |
异步回调地狱(已被 async/await 解决) |
| V8 引擎性能出色 |
单线程(虽有 Worker) |
| 社区活跃,更新快速 |
NPM 依赖地狱 |
10. TypeScript
10.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2012 年(Microsoft,Anders Hejlsberg) |
| 范式 |
面向对象、函数式、多范式 |
| 类型系统 |
静态类型(编译期),超集于 JavaScript |
| 最新版本 |
TypeScript 5.7(2024) |
| 官网 |
https://www.typescriptlang.org |
TypeScript 是 2024 年 GitHub Octoverse 排名第一的语言,大型项目的首选。
10.2 核心特性与语法
// 基础类型
const name: string = "Alice";
const age: number = 30;
const active: boolean = true;
const scores: number[] = [95, 87, 92];
const tuple: [string, number] = ["Alice", 30];
// 联合类型与交叉类型
type StringOrNumber = string | number;
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged; // 交叉类型
// 类型别名 vs 接口
type Point = { x: number; y: number };
interface IPoint { x: number; y: number }
// 接口继承
interface Animal {
name: string;
speak(): string;
}
interface Dog extends Animal {
breed: string;
fetch(): void;
}
// 泛型
function identity<T>(arg: T): T {
return arg;
}
interface Repository<T, ID> {
findById(id: ID): Promise<T | null>;
findAll(): Promise<T[]>;
save(entity: T): Promise<T>;
delete(id: ID): Promise<void>;
}
// 条件类型
type IsArray<T> = T extends any[] ? true : false;
type ElementType<T> = T extends (infer U)[] ? U : never;
// 映射类型
type Readonly<T> = { readonly [K in keyof T]: T[K] };
type Partial<T> = { [K in keyof T]?: T[K] };
type Required<T> = { [K in keyof T]-?: T[K] };
type Pick<T, K extends keyof T> = { [P in K]: T[P] };
// 实用类型示例
interface UserInput {
name: string;
email: string;
password: string;
role: "admin" | "user" | "moderator";
}
type CreateUserDto = Omit<UserInput, "role"> & { role?: UserInput["role"] };
type UpdateUserDto = Partial<Pick<UserInput, "name" | "email">>;
// 装饰器(实验性)
function Log(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${key} with`, args);
return original.apply(this, args);
};
return descriptor;
}
class UserService {
@Log
createUser(name: string, email: string) {
// ...
}
}
// 类型守卫
function isString(value: unknown): value is string {
return typeof value === "string";
}
function processValue(value: string | number | boolean) {
if (isString(value)) {
console.log(value.toUpperCase()); // TypeScript 知道这里是 string
}
}
// 模板字面量类型(TS 4.1+)
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`; // "onClick" | "onFocus" | "onBlur"
10.3 优缺点
| 优点 |
缺点 |
| 静态类型捕获编译期错误 |
需要编译步骤 |
| 出色的 IDE 自动补全 |
大型类型定义可能复杂 |
| 向后兼容 JavaScript |
增加项目配置复杂度 |
| Angular 等框架首选 |
某些第三方库类型定义不完善 |
11. Ruby
11.1 简介与历史
Ruby 以其优雅的语法和"让开发者快乐"的设计哲学著称,Ruby on Rails 曾引领 Web 开发革命。
11.2 核心语法
# 一切皆对象
puts 42.class # Integer
puts "hello".class # String
puts nil.class # NilClass
puts true.class # TrueClass
# 字符串
name = "World"
puts "Hello, #{name}!" # 字符串插值
puts 'No #{interpolation}' # 单引号无插值
# 数组
arr = [1, 2, 3, 4, 5]
puts arr.map { |x| x * 2 }.inspect # [2, 4, 6, 8, 10]
puts arr.select(&:odd?).inspect # [1, 3, 5]
puts arr.reduce(:+) # 15
# 哈希(Hash/字典)
person = { name: "Alice", age: 30, city: "Tokyo" }
person.each { |key, value| puts "#{key}: #{value}" }
# Symbol
status = :active
puts status.to_s # "active"
# Range
(1..5).each { |i| puts i }
puts (1...5).to_a.inspect # [1, 2, 3, 4](不含 5)
# 条件表达式
age = 20
category = if age < 18 then "minor"
elsif age < 65 then "adult"
else "senior"
end
# unless(等价于 if not)
puts "Not empty" unless arr.empty?
# 方法
def greet(name, greeting: "Hello")
"#{greeting}, #{name}!"
end
puts greet("Alice") # Hello, Alice!
puts greet("Bob", greeting: "Hi") # Hi, Bob!
# 块(Block)
3.times { |i| puts "Step #{i}" }
[1, 2, 3].each_with_object([]) { |x, acc| acc << x * 2 }
# Proc 和 Lambda
square = ->(x) { x ** 2 }
double = proc { |x| x * 2 }
# yield
def with_logging
puts "Starting..."
result = yield
puts "Done. Result: #{result}"
result
end
with_logging { 42 }
类与模块
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 简例
# 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
11.3 优缺点
| 优点 |
缺点 |
| 语法优雅,开发效率高 |
执行速度较慢 |
| Rails 框架生产力极高 |
相比 Python/JS,社区规模缩小 |
| 元编程能力强 |
并发模型 GIL 限制(MRI) |
| 测试文化好(RSpec) |
部署和运维相对复杂 |
12. PHP
12.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1994 年(Rasmus Lerdorf) |
| 范式 |
过程式、面向对象、函数式 |
| 类型系统 |
动态类型(PHP 7+ 支持类型声明) |
| 最新版本 |
PHP 8.4(2024) |
| 官网 |
https://www.php.net |
PHP 驱动全球约 77% 的网站,WordPress、Facebook(早期)等均基于 PHP 构建。
12.2 核心语法
<?php
// 类型声明(PHP 7+)
declare(strict_types=1);
// 变量($ 前缀)
$name = "Alice";
$age = 30;
$scores = [95, 87, 92];
// 字符串插值
echo "Hello, $name!";
echo "Age: {$age}";
// 数组
$fruits = ["apple", "banana", "cherry"];
$person = ["name" => "Alice", "age" => 30]; // 关联数组
// 函数
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
// 箭头函数(PHP 7.4+)
$double = fn($x) => $x * 2;
$evens = array_filter([1,2,3,4,5], fn($n) => $n % 2 === 0);
// 类(PHP 8)
class User {
public function __construct(
private readonly int $id,
private string $name,
private string $email,
) {}
public function getName(): string { return $this->name; }
// 命名参数(PHP 8)
public static function create(
string $name,
string $email,
int $id = 0
): self {
return new self($id, $name, $email);
}
}
$user = User::create(name: "Alice", email: "alice@example.com");
// 枚举(PHP 8.1)
enum Status: string {
case Active = 'active';
case Inactive = 'inactive';
case Pending = 'pending';
public function label(): string {
return match($this) {
Status::Active => 'Active User',
Status::Inactive => 'Inactive User',
Status::Pending => 'Pending Approval',
};
}
}
// Match 表达式(PHP 8)
$result = match(true) {
$age < 18 => 'minor',
$age < 65 => 'adult',
default => 'senior',
};
// Fibers(PHP 8.1,协程)
$fiber = new Fiber(function(): string {
$value = Fiber::suspend('first');
echo "Got: $value\n";
return 'final';
});
$result1 = $fiber->start(); // first
$result2 = $fiber->resume('hello'); // Got: hello
// Nullsafe 操作符(PHP 8)
$city = $user?->getAddress()?->getCity();
Laravel 框架示例
// routes/api.php
Route::apiResource('users', UserController::class);
// app/Http/Controllers/UserController.php
class UserController extends Controller {
public function index(Request $request): JsonResponse {
$users = User::query()
->when($request->search, fn($q, $s) => $q->where('name', 'like', "%$s%"))
->with(['posts', 'profile'])
->paginate(15);
return response()->json($users);
}
public function store(StoreUserRequest $request): JsonResponse {
$user = User::create($request->validated());
event(new UserCreated($user));
return response()->json($user, 201);
}
}
12.3 优缺点
| 优点 |
缺点 |
| 部署极其简单 |
历史设计不一致(函数命名混乱) |
| Web 开发生态成熟(Laravel、WordPress) |
安全问题历史较多 |
| PHP 8 性能大幅提升 |
不适合 CPU 密集型任务 |
| Composer 包管理完善 |
语言设计缺乏一致性 |
| 托管服务支持广泛 |
相较现代语言较为落后 |
13. Swift
13.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2014 年(Apple) |
| 范式 |
面向对象、函数式、协议导向编程 |
| 类型系统 |
静态强类型、类型推断 |
| 最新版本 |
Swift 6.0(2024) |
| 官网 |
https://swift.org |
Swift 是 Apple 生态(iOS、macOS、watchOS、tvOS)的首选语言,也在 Swift on Server 方向快速成长。
13.2 核心语法
// 变量与常量
var mutableValue = 42
let immutableValue = "Hello"
// 可选类型(Optional)
var optionalName: String? = nil
let name = optionalName ?? "Unknown" // 空值合并
// 可选绑定
if let actualName = optionalName {
print("Name: \(actualName)")
}
// guard let(提前退出)
func processUser(id: Int?) {
guard let userId = id, userId > 0 else {
print("Invalid user ID")
return
}
print("Processing user: \(userId)")
}
// 枚举
enum Direction: CaseIterable {
case north, south, east, west
var opposite: Direction {
switch self {
case .north: return .south
case .south: return .north
case .east: return .west
case .west: return .east
}
}
}
// 带关联值的枚举
enum NetworkResult<T> {
case success(T)
case failure(Error)
case loading
}
// 结构体(值类型)
struct Point {
var x: Double
var y: Double
func distance(to other: Point) -> Double {
sqrt(pow(x - other.x, 2) + pow(y - other.y, 2))
}
}
// 类(引用类型)
class Vehicle {
var brand: String
var speed: Double
init(brand: String, speed: Double) {
self.brand = brand
self.speed = speed
}
func describe() -> String {
"\(brand) at \(speed) km/h"
}
}
// 协议(Protocol)
protocol Drawable {
func draw()
var color: String { get }
}
protocol Resizable {
func resize(by factor: Double)
}
// 协议组合
typealias Shape = Drawable & Resizable
// 扩展
extension String {
var isPalindrome: Bool {
self == String(self.reversed())
}
func trimmed() -> String {
trimmingCharacters(in: .whitespacesAndNewlines)
}
}
// 闭包
let numbers = [1, 2, 3, 4, 5]
let squared = numbers.map { $0 * $0 }
let evens = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0, +)
// 泛型
func swap<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
// 错误处理
enum FileError: Error {
case notFound
case permissionDenied
case corrupted(reason: String)
}
func readFile(at path: String) throws -> String {
guard path.hasSuffix(".txt") else {
throw FileError.notFound
}
return "File content"
}
do {
let content = try readFile(at: "data.txt")
print(content)
} catch FileError.notFound {
print("File not found")
} catch {
print("Error: \(error)")
}
Swift 并发(async/await,Swift 5.5+)
import Foundation
// Actor(线程安全)
actor BankAccount {
private var balance: Double
init(balance: Double) {
self.balance = balance
}
func deposit(_ amount: Double) {
balance += amount
}
func withdraw(_ amount: Double) async throws -> Double {
guard balance >= amount else {
throw BankError.insufficientFunds
}
balance -= amount
return balance
}
var currentBalance: Double { balance }
}
// async/await
func fetchUserAndPosts(userId: Int) async throws -> (User, [Post]) {
async let user = fetchUser(id: userId)
async let posts = fetchPosts(for: userId)
return try await (user, posts) // 并发执行
}
// Task 和 TaskGroup
func processImages(_ urls: [URL]) async -> [ProcessedImage] {
await withTaskGroup(of: ProcessedImage?.self) { group in
for url in urls {
group.addTask {
try? await downloadAndProcess(url)
}
}
var results: [ProcessedImage] = []
for await result in group {
if let r = result { results.append(r) }
}
return results
}
}
13.3 优缺点
| 优点 |
缺点 |
| Apple 生态首选,性能优秀 |
主要局限于 Apple 平台 |
| 安全特性(可选类型、内存安全) |
跨平台支持有限 |
| 语法现代简洁 |
ABI 稳定较晚(Swift 5.0) |
| Swift Concurrency 并发模型强大 |
学习曲线相比 Python 较陡 |
14. Dart
14.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2011 年(Google) |
| 范式 |
面向对象、函数式 |
| 类型系统 |
静态强类型(健全 null 安全,Dart 2.12+) |
| 最新版本 |
Dart 3.5(2024) |
| 官网 |
https://dart.dev |
Dart 因 Flutter 框架而大放异彩,是跨平台(iOS/Android/Web/Desktop)应用开发的首选语言。
14.2 核心语法
// 变量与类型
var name = 'Alice'; // 类型推断
String city = 'Tokyo';
int age = 30;
double height = 1.65;
bool isStudent = false;
final pi = 3.14159; // 运行时常量
const MAX = 100; // 编译期常量
// Null 安全(Dart 2.12+)
String? nullableName = null; // 可空
String nonNullName = 'Bob'; // 非空
String len = nullableName?.length.toString() ?? 'null';
// 列表和Map
List<int> numbers = [1, 2, 3, 4, 5];
Map<String, dynamic> user = {'name': 'Alice', 'age': 30};
Set<String> tags = {'dart', 'flutter', 'mobile'};
// 类
class Animal {
final String name;
int age;
Animal(this.name, this.age); // 简洁构造函数
// 命名构造函数
Animal.puppy(String name) : this(name, 0);
void speak() => print('$name makes a sound');
@override
String toString() => 'Animal($name, $age)';
}
class Dog extends Animal {
final String breed;
Dog(String name, int age, this.breed) : super(name, age);
@override
void speak() => print('$name: Woof!');
}
// Mixin
mixin Swimmer {
void swim() => print('$runtimeType is swimming');
}
class Duck extends Animal with Swimmer {
Duck() : super('Duck', 1);
}
// 异步
Future<String> fetchData(String url) async {
await Future.delayed(const Duration(seconds: 1));
return 'Data from $url';
}
// Stream
Stream<int> countdown(int from) async* {
for (int i = from; i >= 0; i--) {
await Future.delayed(const Duration(seconds: 1));
yield i;
}
}
// 泛型
class Pair<A, B> {
final A first;
final B second;
const Pair(this.first, this.second);
}
// 扩展方法(Dart 2.7+)
extension StringExt on String {
bool get isPalindrome => this == split('').reversed.join();
String capitalize() => isEmpty ? this : '${this[0].toUpperCase()}${substring(1)}';
}
print('racecar'.isPalindrome); // true
Flutter 示例(简化)
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue)),
home: const CounterPage(),
);
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text('$_count', style: const TextStyle(fontSize: 48)),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
14.3 优缺点
| 优点 |
缺点 |
| Flutter 跨平台开发的最佳伴侣 |
独立于 Flutter 使用场景有限 |
| 健全的 null 安全 |
相比 JS/TS 生态较小 |
| AOT + JIT 编译,性能优秀 |
学习时需同时学 Flutter |
| 语法友好,类 Java/C# |
Web 端 Dart 支持尚在成熟 |
15. R
15.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1993 年(Ross Ihaka & Robert Gentleman,基于 S 语言) |
| 范式 |
函数式、面向对象(S3/S4/R5/R6) |
| 类型系统 |
动态类型 |
| 最新版本 |
R 4.4(2024) |
| 官网 |
https://www.r-project.org |
R 是统计计算和数据可视化的专用语言,在学术研究、生物信息学和数据分析领域广泛使用。
15.2 核心语法
# 基础数据类型
x <- 42L # 整数
y <- 3.14 # 浮点数
name <- "Alice" # 字符串
flag <- TRUE # 布尔值
# 向量(R 的核心数据结构)
v <- c(1, 2, 3, 4, 5)
v2 <- 1:10 # 序列
v3 <- seq(0, 1, 0.1) # 等差序列
# 向量操作(向量化)
v * 2 # 每个元素乘以 2
v[v > 3] # 条件筛选:c(4, 5)
sum(v) # 15
mean(v) # 3
sd(v) # 标准差
# 矩阵
m <- matrix(1:9, nrow=3, ncol=3)
m[2, 3] # 第2行第3列
t(m) # 转置
# 数据框(data.frame)
df <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
score = c(85.5, 92.0, 78.3)
)
df$age # 访问列
df[df$age > 28, ] # 过滤行
nrow(df); ncol(df)
# 列表
lst <- list(
numbers = 1:5,
text = "hello",
nested = list(a = 1, b = 2)
)
lst$numbers
lst[["text"]]
# 函数
calculate_stats <- function(x, na.rm = TRUE) {
list(
mean = mean(x, na.rm = na.rm),
median = median(x, na.rm = na.rm),
sd = sd(x, na.rm = na.rm),
range = range(x, na.rm = na.rm)
)
}
# apply 族
sapply(1:5, function(x) x^2) # [1] 1 4 9 16 25
lapply(df, class) # 每列的类型
tapply(df$score, df$name, mean) # 分组均值
# tidyverse 风格(推荐)
library(dplyr)
library(ggplot2)
result <- df |>
filter(age > 25) |>
mutate(grade = ifelse(score >= 90, "A", "B")) |>
arrange(desc(score)) |>
select(name, score, grade)
# 可视化(ggplot2)
ggplot(df, aes(x = age, y = score, color = name)) +
geom_point(size = 3) +
geom_smooth(method = "lm") +
labs(title = "Score vs Age", x = "Age", y = "Score") +
theme_minimal()
# 统计建模
model <- lm(score ~ age, data = df)
summary(model)
predict(model, newdata = data.frame(age = 28))
15.3 生态系统
| 包 |
说明 |
| tidyverse |
数据科学工具包(dplyr、ggplot2、tidyr 等) |
| caret / tidymodels |
机器学习框架 |
| Bioconductor |
生物信息学 |
| Shiny |
交互式 Web 应用 |
| RMarkdown / Quarto |
可重复研究报告 |
| data.table |
高性能数据处理 |
16. Julia
16.1 简介与历史
Julia 的目标:"像 Python 一样易写,像 C 一样快"。通过 LLVM JIT 编译实现接近 C 的性能,专为科学计算和数值分析设计。
16.2 核心语法
# 基础语法
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))
16.3 优缺点
| 优点 |
缺点 |
| 接近 C 的数值计算性能 |
首次编译(TTFX)较慢 |
| 多重分派极为强大 |
生态系统小于 Python/R |
| 可读性好,语法接近数学符号 |
错误信息有时不友好 |
| 原生支持并行和分布式计算 |
社区和工作岗位较少 |
17. Lua
17.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1993 年(巴西 PUC-Rio 大学) |
| 范式 |
过程式、面向对象(通过 metatables)、函数式 |
| 类型系统 |
动态类型 |
| 最新版本 |
Lua 5.4(2020)/ LuaJIT |
| 官网 |
https://www.lua.org |
Lua 以其轻量(核心库仅约 248KB)、可嵌入性和高效性著称,是游戏脚本引擎的首选。
17.2 核心语法
-- 变量(默认全局)
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
17.3 典型应用
- 游戏脚本:World of Warcraft、Roblox、LÖVE 2D
- 嵌入式脚本:Redis、Nginx(OpenResty)、Wireshark
- 配置语言:NeoVim 配置
- IoT:NodeMCU(ESP8266/ESP32)
18. Perl
18.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1987 年(Larry Wall) |
| 范式 |
多范式:过程式、面向对象、函数式 |
| 类型系统 |
动态类型 |
| 最新版本 |
Perl 5.38(2023)/ Perl 7(开发中)/ Raku(Perl 6 重命名) |
| 官网 |
https://www.perl.org |
Perl 以其强大的正则表达式和文本处理能力著称,曾是 Web CGI 脚本和系统管理的主力语言。
18.2 核心语法
#!/usr/bin/perl
use strict;
use warnings;
# 变量($ 标量,@ 数组,% 哈希)
my $name = "Alice";
my $age = 30;
my @colors = ("red", "green", "blue");
my %person = (name => "Bob", age => 25);
# 字符串操作
print "Hello, $name!\n";
print "Age: " . $age . "\n"; # 连接用 .
# 正则表达式(Perl 的强项)
my $text = "The quick brown fox jumps over the lazy dog";
if ($text =~ /(\w+)\s+fox/) {
print "Before fox: $1\n"; # quick
}
# 替换
(my $modified = $text) =~ s/fox/cat/g;
# 全局匹配
my @words = ($text =~ /\b\w{4}\b/g); # 所有4字母单词
# 数组操作
push @colors, "yellow";
my $last = pop @colors;
unshift @colors, "black";
my $first = shift @colors;
my @sorted = sort @colors;
my @filtered = grep { /^r/ } @colors; # 以 r 开头
my @upper = map { uc } @colors; # 全部大写
# 哈希
$person{city} = "Tokyo";
while (my ($k, $v) = each %person) {
print "$k: $v\n";
}
# 子程序(函数)
sub greet {
my ($name, $greeting) = @_;
$greeting //= "Hello"; # 定义或操作符(//)
return "$greeting, $name!";
}
# 文件操作
open(my $fh, '<', 'file.txt') or die "Cannot open: $!";
while (my $line = <$fh>) {
chomp $line;
print "$line\n";
}
close $fh;
# 引用(用于复杂数据结构)
my $aref = [1, 2, 3]; # 数组引用
my $href = {a => 1, b => 2}; # 哈希引用
print $aref->[0]; # 1
print $href->{a}; # 1
18.3 优缺点
| 优点 |
缺点 |
| 强大的文本处理和正则表达式 |
语法复杂,"write-only"之名 |
| CPAN 拥有大量模块 |
现代语言已取代其大部分场景 |
| 系统管理脚本强大 |
可读性差,维护困难 |
| 跨平台 |
社区萎缩 |
19. Haskell
19.1 简介与历史
Haskell 是学术界和金融领域(Barclays、JP Morgan)的重要语言,以其强大的类型系统和数学优雅性著称。Stack Overflow 薪资调查中 Haskell 开发者薪资名列前茅。
19.2 核心特性
- 纯函数:没有副作用,相同输入永远产生相同输出
- 惰性求值:表达式仅在需要时才计算(可处理无限列表)
- 强类型系统:Hindley-Milner 类型推断
- 类型类(Typeclass):类似接口的多态机制
- Monad:处理副作用的抽象(IO、Maybe、Either、State 等)
- 函数组合:函数是一等公民
19.3 核心语法
-- 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
19.4 优缺点
| 优点 |
缺点 |
| 极强的类型安全,编译即正确 |
学习曲线极陡(Monad 等抽象) |
| 代码简洁,表达力强 |
性能调优复杂(惰性求值) |
| 并发安全(纯函数无副作用) |
生态系统较小 |
| 金融建模的高薪领域 |
招聘市场较小 |
20. Scala
20.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2004 年(Martin Odersky,EPFL) |
| 范式 |
面向对象 + 函数式(多范式) |
| 类型系统 |
静态强类型,类型推断 |
| 最新版本 |
Scala 3.5(2024) |
| 运行时 |
JVM(主要)、Scala.js(JS)、Scala Native |
| 官网 |
https://scala-lang.org |
Scala 是大数据生态的核心语言,Apache Spark、Kafka 等均用 Scala 编写。
20.2 核心语法
// 不可变值(推荐)vs 可变变量
val name = "Alice" // 不可变(类型推断)
var age = 30 // 可变
val pi: Double = 3.14 // 显式类型
// 样例类(Case Class)------不可变数据 + 自动 equals/hashCode/copy
case class Point(x: Double, y: Double) {
def distanceTo(other: Point): Double =
math.sqrt(math.pow(x - other.x, 2) + math.pow(y - other.y, 2))
}
val p1 = Point(0, 0)
val p2 = Point(3, 4)
println(p1.distanceTo(p2)) // 5.0
val p3 = p1.copy(x = 1.0) // 复制并修改
// 密封 trait + 样例类(代数数据类型)
sealed trait Result[+A]
case class Success[A](value: A) extends Result[A]
case class Failure(error: String) extends Result[Nothing]
case object Empty extends Result[Nothing]
// 模式匹配
def processResult[A](result: Result[A]): String = result match {
case Success(v) => s"Success: $v"
case Failure(e) => s"Error: $e"
case Empty => "No result"
}
// 集合操作(函数式)
val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val result = numbers
.filter(_ % 2 == 0)
.map(_ * _ )
.foldLeft(0)(_ + _)
// for 推导式(Monad 语法糖)
val pairs = for {
x <- 1 to 3
y <- 1 to 3
if x != y
} yield (x, y)
// Option(无 null)
def safeDivide(a: Double, b: Double): Option[Double] =
if (b == 0) None else Some(a / b)
val result2 = for {
x <- safeDivide(10, 2)
y <- safeDivide(x, 5)
} yield x + y // Some(7.0)
// 特征(Trait)
trait Animal {
def name: String
def speak(): String
def describe: String = s"$name says ${speak()}"
}
trait Domesticated extends Animal {
def owner: String
}
class Dog(val name: String, val owner: String)
extends Animal with Domesticated {
def speak() = "Woof!"
}
// 隐式转换(Scala 2)/ 扩展方法(Scala 3)
extension (s: String)
def isPalindrome: Boolean = s == s.reverse
def wordCount: Int = s.split("\\s+").length
"hello world".wordCount // 2
// Future(异步)
import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.ExecutionContext.Implicits.global
def fetchUser(id: Int): Future[String] =
Future { Thread.sleep(100); s"User $id" }
val result3 = for {
user <- fetchUser(1)
profile <- fetchUser(2)
} yield s"$user + $profile"
20.3 Spark 示例
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder()
.appName("WordCount")
.master("local")
.getOrCreate()
import spark.implicits._
val wordCounts = spark.read.textFile("input.txt")
.flatMap(_.split("\\s+"))
.groupBy("value")
.count()
.orderBy($"count".desc)
wordCounts.show(20)
20.4 优缺点
| 优点 |
缺点 |
| JVM 生态 + 函数式两全 |
学习曲线陡(尤其高级特性) |
| Apache Spark 首选语言 |
编译速度慢 |
| 表达力极强 |
代码风格不统一 |
| 类型系统强大 |
新旧版本(Scala 2/3)兼容问题 |
21. Erlang
21.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
1986 年(爱立信,Joe Armstrong 等) |
| 范式 |
函数式、并发、分布式 |
| 类型系统 |
动态类型(Dialyzer 静态分析) |
| 最新版本 |
OTP 27(2024) |
| 官网 |
https://www.erlang.org |
Erlang 为电信级系统设计,WhatsApp 用 Erlang 以 50 名工程师支撑 4.5 亿用户。其 BEAM 虚拟机是业界容错并发的顶尖实现。
21.2 核心特性
- Actor 并发模型:轻量级进程(Erlang process,非 OS thread)
- "Let it crash" 哲学:进程崩溃由 Supervisor 重启
- 热更新:在不停机情况下更新运行中的代码
- 分布式:内置节点间通信
- 不可变数据:所有数据不可变,无共享内存
21.3 核心语法
%% 模块声明
-module(hello).
-export([main/0, factorial/1, fibonacci/1]).
%% Hello World
main() ->
io:format("Hello, World!~n").
%% 模式匹配 + 递归
factorial(0) -> 1;
factorial(N) when N > 0 -> N * factorial(N - 1).
%% 列表处理
fibonacci(0) -> 0;
fibonacci(1) -> 1;
fibonacci(N) -> fibonacci(N-1) + fibonacci(N-2).
%% 列表操作
sum_list([]) -> 0;
sum_list([H|T]) -> H + sum_list(T).
%% 进程(Actor)
start_counter(N) ->
spawn(fun() -> counter(N) end).
counter(N) ->
receive
{increment, From} ->
From ! {ok, N + 1},
counter(N + 1);
{get, From} ->
From ! {value, N},
counter(N);
stop ->
ok
end.
%% 使用进程
demo() ->
Pid = start_counter(0),
Pid ! {increment, self()},
receive
{ok, NewVal} -> io:format("Value: ~p~n", [NewVal])
end,
Pid ! stop.
%% Supervisor 树(OTP)
-behaviour(supervisor).
init([]) ->
Children = [
{worker1, {worker_module, start_link, []},
permanent, 5000, worker, [worker_module]}
],
{ok, {{one_for_one, 5, 10}, Children}}.
22. Elixir
22.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2011 年(José Valim) |
| 范式 |
函数式、并发、分布式 |
| 类型系统 |
动态类型 |
| 最新版本 |
Elixir 1.18(2024) |
| 运行时 |
BEAM(Erlang VM) |
| 官网 |
https://elixir-lang.org |
Elixir 继承 Erlang BEAM 的并发与容错优势,同时提供 Ruby 风格的优雅语法,Phoenix 框架使其成为高并发 Web 应用的热门选择。
22.2 核心语法
# 基本类型
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 示例
# 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
22.3 优缺点
| 优点 |
缺点 |
| 极高并发(百万级进程) |
动态类型,运行时错误 |
| 容错性极强(OTP Supervisor) |
生态系统比 Ruby/Python 小 |
| Phoenix 性能卓越(WebSocket 百万级连接) |
学习 OTP 有一定曲线 |
| 管道操作符代码可读性极好 |
数字计算性能不如系统语言 |
| 热更新支持 |
Erlang 的某些限制 |
23. Clojure
23.1 简介与历史
| 属性 |
内容 |
| 诞生年份 |
2007 年(Rich Hickey) |
| 范式 |
函数式(Lisp 方言)、并发 |
| 类型系统 |
动态类型 |
| 最新版本 |
Clojure 1.12(2024) |
| 运行时 |
JVM(主要)、ClojureScript(JS)、ClojureCLR |
| 官网 |
https://clojure.org |
Clojure 是现代 Lisp,以不可变数据结构和 STM(软件事务内存)为特色,Stack Overflow 薪资调查中长期位居最高薪资语言之列。
23.2 核心语法
;; Hello World
(println "Hello, World!")
;; 基本数据类型
42 ; 整数
3.14 ; 浮点数
"hello" ; 字符串
true ; 布尔
:keyword ; 关键字(类似 Ruby symbol)
nil ; 空值
;; 不可变集合
(def numbers [1 2 3 4 5]) ; 向量(Vector)
(def colors #{:red :green :blue}) ; 集合(Set)
(def person {:name "Alice" :age 30}) ; 映射(Map)
(def my-list '(1 2 3 4 5)) ; 列表
;; 函数定义
(defn greet
"Greets a person by name."
([name] (greet name "Hello"))
([name greeting] (str greeting ", " name "!")))
(greet "Alice") ; "Hello, Alice!"
(greet "Bob" "Hi") ; "Hi, Bob!"
;; 高阶函数
(map #(* % 2) [1 2 3 4 5]) ; (2 4 6 8 10)
(filter even? [1 2 3 4 5 6]) ; (2 4 6)
(reduce + 0 [1 2 3 4 5]) ; 15
;; 线程宏(->> 管道)
(->> (range 1 11)
(filter odd?)
(map #(* % %))
(reduce +)) ; 165(奇数的平方和)
;; Let 绑定
(let [x 10
y 20
z (+ x y)]
(* z 2)) ; 60
;; 条件
(defn classify [n]
(cond
(neg? n) "negative"
(zero? n) "zero"
(pos? n) "positive"))
;; 递归(loop/recur)
(defn factorial [n]
(loop [acc 1, i n]
(if (<= i 0)
acc
(recur (* acc i) (dec i)))))
;; 不可变数据操作
(def v [1 2 3])
(conj v 4) ; [1 2 3 4](新向量,原不变)
(assoc {:a 1} :b 2) ; {:a 1 :b 2}(新 map)
;; 原子(Atom)------并发状态管理
(def counter (atom 0))
(swap! counter inc) ; 原子更新
(reset! counter 0) ; 重置
@counter ; 解引用,读取值
;; STM 事务(ref)
(def account-a (ref 1000))
(def account-b (ref 500))
(defn transfer [from to amount]
(dosync
(alter from - amount)
(alter to + amount)))
(transfer account-a account-b 200)
[@account-a @account-b] ; [800 700]
;; 宏(Macro)------编译期代码转换
(defmacro unless [condition & body]
`(when (not ~condition)
~@body))
(unless false
(println "This runs"))
;; 协议(Protocol,类似接口)
(defprotocol Shape
(area [shape])
(perimeter [shape]))
(defrecord Circle [radius]
Shape
(area [_] (* Math/PI radius radius))
(perimeter [_] (* 2 Math/PI radius)))
(defrecord Rectangle [width height]
Shape
(area [_] (* width height))
(perimeter [_] (* 2 (+ width height))))
(def c (->Circle 5.0))
(println (area c)) ; 78.53...
;; 懒序列
(def natural-numbers (iterate inc 1))
(take 10 natural-numbers) ; (1 2 3 4 5 6 7 8 9 10)
(def fib-seq
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
(take 10 fib-seq) ; (0 1 1 2 3 5 8 13 21 34)
23.3 优缺点
| 优点 |
缺点 |
| 完全拥抱不可变性 |
Lisp 括号语法对新手不友好 |
| JVM 生态可直接使用 |
动态类型,运行时错误 |
| 强大的 Macro 元编程 |
社区小,职位少 |
| STM 并发模型优雅 |
调试相对困难 |
| REPL 驱动开发效率高 |
启动时间(JVM)较长 |
24. 语言横向对比
24.1 性能对比
| 语言 |
性能级别 |
说明 |
| C |
★★★★★ |
最高,接近汇编 |
| C++ |
★★★★★ |
媲美 C,零成本抽象 |
| Rust |
★★★★★ |
媲美 C/C++ |
| Go |
★★★★ |
接近 C,GC 有停顿 |
| Java |
★★★★ |
JIT 优化后接近 Go |
| Kotlin |
★★★★ |
同 JVM,同 Java |
| C# |
★★★★ |
.NET 优化后优秀 |
| Swift |
★★★★ |
AOT 编译,优秀 |
| Julia |
★★★★ |
JIT 后接近 C |
| Dart |
★★★ |
AOT 编译,较好 |
| Scala |
★★★ |
JVM 有开销 |
| Erlang |
★★★ |
并发优,单线程弱 |
| Elixir |
★★★ |
同 BEAM |
| Ruby |
★★ |
解释型,较慢 |
| Python |
★★ |
CPython 较慢 |
| PHP |
★★ |
PHP 8 JIT 改善 |
| JavaScript |
★★★ |
V8 JIT 优化强 |
| TypeScript |
★★★ |
编译为 JS,同 JS |
| Lua |
★★★★ |
轻量级,较快 |
| Haskell |
★★★ |
GHC 优化后较好 |
| R |
★ |
解释型,向量化快 |
| Clojure |
★★★ |
JVM,启动慢 |
| Perl |
★★ |
解释型 |
24.2 类型系统对比
| 类型系统 |
语言 |
| 静态强类型 |
Rust、Go、Java、Kotlin、C#、Swift、Dart、Scala、Haskell、TypeScript |
| 静态弱类型 |
C、C++ |
| 动态强类型 |
Python、Ruby、Erlang、Elixir、Clojure |
| 动态弱类型 |
JavaScript、PHP、Perl、Lua |
| 动态 + 可选静态 |
Python(类型提示)、PHP 8(声明类型) |
24.3 内存管理对比
| 机制 |
语言 |
| 手动管理 |
C、C++ |
| 所有权/借用检查 |
Rust |
| 垃圾回收(GC) |
Java、Kotlin、C#、Go、Python、Ruby、JS/TS、PHP、Swift(ARC)、Dart、Scala、Erlang、Elixir、Clojure、Haskell |
| 引用计数(ARC) |
Swift、Objective-C |
| 自动(BEAM 进程隔离 GC) |
Erlang、Elixir |
24.4 并发模型对比
| 并发模型 |
语言 |
| 线程 + 共享内存 |
Java、C++、C#、Go |
| Goroutines + Channels(CSP) |
Go |
| Actor 模型 |
Erlang、Elixir(基于 BEAM 进程) |
| async/await |
Python(asyncio)、JavaScript、C#、Rust(tokio)、Dart、Swift |
| 协程 |
Kotlin(Coroutines)、Lua |
| STM(软件事务内存) |
Clojure、Haskell |
| 所有权保证无数据竞争 |
Rust |
24.5 学习曲线
| 难度 |
语言 |
| 较易 |
Python、JavaScript、Ruby、PHP、Go、Lua |
| 中等 |
Java、Kotlin、C#、TypeScript、Dart、Swift、R |
| 较难 |
C、C++、Scala、Erlang、Elixir |
| 困难 |
Rust(借用检查)、Haskell(纯函数式+Monad) |
25. 选型建议
25.1 按场景推荐
| 场景 |
推荐语言 |
理由 |
| 操作系统/驱动 |
C、Rust |
最高控制力和性能 |
| 游戏开发 |
C++(引擎)、C#(Unity 脚本)、Lua(游戏脚本) |
行业标准 |
| Web 后端(高并发) |
Go、Elixir、Rust(actix) |
并发强,性能好 |
| Web 后端(企业级) |
Java(Spring)、C#(.NET)、Kotlin |
生态成熟 |
| Web 后端(快速开发) |
Python(Django/FastAPI)、Ruby(Rails)、PHP(Laravel) |
开发效率高 |
| 前端 |
JavaScript、TypeScript |
唯一选择 |
| 全栈 |
JavaScript/TypeScript(Node.js) |
同语言全栈 |
| AI/机器学习 |
Python |
绝对主导 |
| 数据科学/统计 |
Python、R |
成熟的分析生态 |
| 科学计算/数值分析 |
Python(NumPy)、Julia、R、MATLAB |
专业工具 |
| 大数据处理 |
Scala(Spark)、Python(PySpark) |
行业标准 |
| Android 开发 |
Kotlin、Java |
Google 推荐 |
| iOS/macOS 开发 |
Swift |
Apple 推荐 |
| 跨平台移动 |
Dart(Flutter)、Kotlin Multiplatform |
一码多端 |
| 系统脚本/自动化 |
Python、Bash/Shell、Perl |
高效脚本 |
| 嵌入式/IoT |
C、Rust、Lua(NodeMCU) |
资源约束环境 |
| 区块链 |
Rust、Solidity、Go |
安全与性能 |
| 实时通信/聊天系统 |
Elixir、Erlang、Go |
高并发容错 |
| 金融建模 |
Haskell、Scala、Python、R |
类型安全+数学表达 |
| 学术/研究 |
Python、R、Julia、Haskell |
科学计算与FP研究 |
| 函数式编程学习 |
Haskell、Clojure、Elixir |
纯FP/实用FP |
| 嵌入式脚本语言 |
Lua、JavaScript(V8) |
轻量可嵌入 |
| 云原生基础设施 |
Go、Rust |
Docker/K8s 等 |
25.2 语言学习路径推荐
初学者路径
Python(入门)→ JavaScript(Web)→ Java 或 Go(后端)
系统编程路径
C(基础)→ C++(进阶)→ Rust(现代安全)
全栈 Web 路径
HTML/CSS → JavaScript → TypeScript → Node.js/React → Python/Go(后端)
数据科学路径
Python(基础)→ Pandas/NumPy → scikit-learn → PyTorch/TensorFlow → R(统计)→ Julia(高性能)
函数式编程路径
JavaScript(函数式入门)→ Elixir 或 Scala(实用 FP)→ Haskell(纯 FP)
移动开发路径
Swift(iOS)/ Kotlin(Android)→ Dart/Flutter(跨平台)
25.3 2024-2025 趋势总结
- Rust 持续增长,Linux 内核、Windows 内核、Android 都在纳入 Rust
- TypeScript 在 2024 年 GitHub Octoverse 中跃升第一
- Python 在 AI 浪潮中保持 TIOBE 第一地位
- Go 仍是云原生基础设施的主导,但 TIOBE 有所下滑
- Kotlin Multiplatform 跨平台潜力巨大
- Elixir/Phoenix 在高并发 Web 领域持续升温
- Julia 在科学计算领域稳步成长
- Java 通过 Project Loom(虚拟线程)和 GraalVM 保持竞争力
附录
A. 各语言官方文档链接
B. 推荐书单
| 语言 |
书目 |
| C |
《C程序设计语言》(K&R) |
| C++ |
《C++ Primer》、《Effective Modern C++》 |
| Rust |
《The Rust Programming Language》(免费在线) |
| Go |
《The Go Programming Language》 |
| Java |
《Effective Java》、《Java核心技术》 |
| Python |
《流畅的Python》、《Python Cookbook》 |
| JavaScript |
《JavaScript权威指南》、《你不知道的JS》 |
| Haskell |
《Learn You a Haskell for Great Good!》(免费在线) |
| Scala |
《Programming in Scala》 |
| Elixir |
《Programming Elixir》(Dave Thomas) |
| Clojure |
《Clojure for the Brave and True》(免费在线) |
C. 包管理器速查
| 语言 |
包管理器 |
安装命令示例 |
| Rust |
Cargo |
cargo add serde |
| Go |
go mod |
go get github.com/gin-gonic/gin |
| Java |
Maven/Gradle |
mvn install / gradle build |
| Kotlin |
Gradle |
gradle build |
| Python |
pip/poetry/uv |
pip install requests |
| JavaScript |
npm/yarn/pnpm |
npm install express |
| TypeScript |
npm |
npm install typescript |
| Ruby |
gem/bundler |
gem install rails |
| PHP |
Composer |
composer require laravel/laravel |
| Swift |
SPM |
swift package add-dependency |
| Dart |
pub |
dart pub add http |
| R |
CRAN |
install.packages("tidyverse") |
| Julia |
Pkg |
] add DataFrames |
| Haskell |
Cabal/Stack |
cabal install |
| Scala |
sbt |
sbt compile |
| Elixir |
Mix/Hex |
mix deps.get |
| Clojure |
Leiningen/deps.edn |
lein deps |