rust的type


Rust 中的 type

Rust 中的 type 关键字用于创建类型别名(type alias),类似于 Python 中的类型注解或类型别名功能。

// 基本类型别名
type Kilometers = i32;
type Thunk = Box<dyn Fn() + Send + 'static>;
// 复杂类型别名
type Result<T> = std::result::Result<T, MyError>;
type PinBoxFut<T> = Pin<Box<dyn Future<Output = T> + Send>>;

Python 中的类似概念

1. 类型注解(Type Hints)

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(结构化字典)

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(创建不同的类型)

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
type ServiceResult<T> = Result<T, ServiceError>;
type EventHandler = Box<dyn Fn(Event) -> Result<(), Error>>;
fn process_data() -> ServiceResult<String> {
    // 实现
    Ok("data".to_string())
}
# 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"

声明:一代明君的小屋|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - rust的type


欢迎来到我的小屋