rust的type 最后更新时间:2025年10月27日 ## Rust 中的 `type` Rust 中的 `type` 关键字用于创建类型别名(type alias),类似于 Python 中的类型注解或类型别名功能。 ```rust // 基本类型别名 type Kilometers = i32; type Thunk = Box; // 复杂类型别名 type Result = std::result::Result; type PinBoxFut = Pin + Send>>; ``` ## Python 中的类似概念 ### 1. 类型注解(Type Hints) ```python from typing import List, Dict, Tuple, Union, Callable # 类型别名 Vector = List[float] ConnectionOptions = Dict[str, str] Address = Tuple[str, int] Callback = Callable[[str], None] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # 使用联合类型 Number = Union[int, float] ``` ### 2. TypedDict(结构化字典) ```python from typing import TypedDict class Person(TypedDict): name: str age: int email: str # 使用 person: Person = { "name": "Alice", "age": 30, "email": "alice@example.com" } ``` ### 3. NewType(创建不同的类型) ```python from typing import NewType UserId = NewType('UserId', int) some_id = UserId(5) # UserId 是 int 的子类型,但被视为不同类型 def get_user(user_id: UserId) -> str: return f"User {user_id}" ``` ## 主要区别 1. **编译时检查**: - Rust 的 `type` 在编译时会被完全替换,不提供运行时安全保障 - Python 的类型注解主要用于静态分析工具(如 mypy),运行时无影响 2. **NewType vs type**: - Rust 的 `type` 不创建新类型,只是别名 - Python 的 `NewType` 创建语义上的新类型 3. **复杂类型**: - Rust 的 `type` 可以用于简化复杂的泛型类型 - Python 使用 `typing` 模块达到类似效果 ## 实际应用示例 ```rust // Rust type ServiceResult = Result; type EventHandler = Box Result<(), Error>>; fn process_data() -> ServiceResult { // 实现 Ok("data".to_string()) } ``` ```python # Python from typing import TypeAlias, Callable, Result ServiceResult: TypeAlias = Result[str, Exception] EventHandler: TypeAlias = Callable[[Event], Result[None, Error]] def process_data() -> ServiceResult: # 实现 return "data" ```
Comments | NOTHING