📚 标准库

TLL 标准库提供核心模块:输入输出、数学、字符串、集合、时间、JSON、HTTP、文件系统、加密、测试、Agent 运行时。

1. 核心模块一览

模块说明
io输入输出(println, read, 文件)
math数学函数(sqrt, sin, cos, 等)
strings字符串操作
collectionsList, Map, Set, 等
time日期和时间
jsonJSON 序列化/反序列化
httpHTTP 客户端和服务端
fs文件系统操作
os操作系统级操作
crypto加密原语
testing测试框架
agentAgent 系统运行时

2. io — 输入输出

import io

fn main() {
    // 输出
    io.println("Hello, World!")
    io.print("no newline")

    // 输入
    let name = io.read_line("What is your name? ")
    io.println("Hello, {name}!")

    // 文件操作
    let content = io.read_file("data.txt")
    io.write_file("output.txt", content)
}

3. math — 数学

import math

fn main() {
    let x = math.sqrt(16.0)      // 4.0
    let y = math.sin(math.pi / 2) // 1.0
    let z = math.pow(2.0, 10.0)   // 1024.0
    let r = math.round(3.7)         // 4
    let f = math.floor(3.7)         // 3
    let c = math.ceil(3.2)          // 4
    let a = math.abs(-5)             // 5
    let mx = math.max(3, 7)          // 7
    let mn = math.min(3, 7)          // 3
}

4. strings — 字符串

import strings

fn main() {
    let s = "Hello, World!"

    let len = s.len()               // 13
    let upper = strings.to_upper(s) // "HELLO, WORLD!"
    let lower = strings.to_lower(s) // "hello, world!"
    let trimmed = strings.trim("  hi  ") // "hi"
    let parts = strings.split(s, ", ")    // ["Hello", "World!"]
    let joined = strings.join(parts, " ") // "Hello World!"
    let replaced = strings.replace(s, "World", "TLL") // "Hello, TLL!"
    let contains = strings.contains(s, "World") // true
    let starts = strings.starts_with(s, "Hello") // true
    let ends = strings.ends_with(s, "!") // true
    let substr = strings.substring(s, 0, 5) // "Hello"
}

5. collections — 集合

import collections

fn main() {
    // List
    let mut list = List[int].new()
    list.push(1)
    list.push(2)
    list.push(3)
    let len = list.len()      // 3
    let first = list.get(0)   // 1
    list.set(0, 10)
    let popped = list.pop()   // 3
    let contains = list.contains(2) // true
    let mapped = list.map(fn(x) = x * 2) // [20, 4]
    let filtered = list.filter(fn(x) = x > 5) // [10]
    let sum = list.reduce(0, fn(acc, x) = acc + x) // 12

    // Map
    let mut map = Map[str, int].new()
    map.set("alice", 95)
    map.set("bob", 87)
    let score = map.get("alice") // 95
    let has = map.has_key("bob") // true
    map.delete("bob")
    let keys = map.keys() // ["alice"]
    let values = map.values() // [95]

    // Set
    let mut set = Set[int].new()
    set.add(1)
    set.add(2)
    set.add(1) // 重复,忽略
    let size = set.len() // 2
}

6. json — JSON

import json

struct User {
    name: str,
    age: int,
}

fn main() {
    let user = User { name: "Alice", age: 30 }

    // 序列化
    let serialized = json.to_string(user)
    io.println(serialized) // {"name":"Alice","age":30}

    // 格式化输出
    let pretty = json.to_string_pretty(user, indent: 2)

    // 反序列化
    let deserialized: User = json.from_string(serialized)
    io.println(deserialized.name)

    // 动态 JSON
    let data = json.parse('{"key": "value", "num": 42}')
    let value = data["key"].as_str()
    let num = data["num"].as_int()
}

7. http — HTTP

import http

fn main() {
    // 客户端
    let response = http.get("https://api.example.com/users")
    let body = response.text()
    let status = response.status_code // 200

    let post_response = http.post("https://api.example.com/users",
        headers: {"Content-Type": "application/json"},
        body: '{"name":"Alice"}'
    )

    // 服务端(结合 api 声明)
    // 见「一等公民」章节的 API 定义
}

8. time — 时间

import time

fn main() {
    let now = time.now()
    let timestamp = now.unix()
    let formatted = now.format("YYYY-MM-DD HH:mm:ss")

    let duration = time.Duration.from_seconds(3600)
    let later = now.add(duration)
    let diff = later.difference(now)
}

9. testing — 测试框架

import testing

fn test_addition() {
    testing.assert_eq(2 + 2, 4)
}

fn test_string_length() {
    let s = "hello"
    testing.assert_eq(s.len(), 5)
    testing.assert(s.contains("ell"))
}

fn test_async_feature() async {
    let result = await some_async_function()
    testing.assert(result.is_ok())
}

fn test_should_panic() {
    testing.should_panic(fn() {
        panic("expected")
    })
}

test_ 前缀的函数会被 tll test 自动发现并运行。