跳到正文
教程首页
DartCH 03ch03_types_collections

ch03-types-collections

Dart 类型系统与集合:类、泛型、List/Map/Set、null 安全。完整工程共 10 个文件,其中 10 个文本源文件可在下面在线阅读。

10

在线文本文件

1,160

源码行数

dart / yaml / text

语言

17 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

darttextyaml

10 text files · 1,160 lines

dartlib/money.dart
/// 值类型(value type):用 `operator ==` + `hashCode` 手写结构相等。
///
/// 对照 C:struct 赋值默认按值拷贝,`a == b` 需要逐字段比较(或用 `memcmp` 这种危险做法)。
/// 对照 Go:struct 的 `==` 自动逐字段比较(如果字段都可比较),slice/map 则不可比较。
/// 对照 Dart:**默认 `==` 是引用相等**(`identical`),想按值比较必须自己重写。
library;

/// 金额:以"分"为单位的整数 + 币种。
///
/// 为什么不用 double 存钱?与 C/Go 一样——二进制浮点表示不了 0.1。
class Money implements Comparable<Money> {
  const Money(this.cents, {this.currency = 'CNY'});

  /// 命名构造函数 / 工厂构造函数:`factory` 可以返回缓存对象或子类型,
  /// 这里用来做"元 → 分"的单位换算。
  factory Money.fromYuan(num yuan, {String currency = 'CNY'}) =>
      Money((yuan * 100).round(), currency: currency);

  final int cents;
  final String currency;

  double get yuan => cents / 100;

  bool get isNegative => cents < 0;

  Money operator +(Money other) {
    _requireSameCurrency(other);
    return Money(cents + other.cents, currency: currency);
  }

  Money operator -(Money other) {
    _requireSameCurrency(other);
    return Money(cents - other.cents, currency: currency);
  }

  void _requireSameCurrency(Money other) {
    if (other.currency != currency) {
      // Dart 的错误也是"抛异常",没有 Go 的 error 返回值、也不返回 C 的错误码。
      throw ArgumentError('币种不一致: $currency vs ${other.currency}');
    }
  }

  /// 值相等:字段逐个比较。`other is Money` 必须先判,否则访问字段会崩。
  @override
  bool operator ==(Object other) =>
      other is Money && other.cents == cents && other.currency == currency;

  /// 重写 `==` 必须同时重写 `hashCode`,否则放不进 Set / 当不了 Map 的 key。
  @override
  int get hashCode => Object.hash(cents, currency);

  @override
  int compareTo(Money other) {
    _requireSameCurrency(other);
    return cents.compareTo(other.cents);
  }

  @override
  String toString() => '${yuan.toStringAsFixed(2)} $currency';
}

/// 增强枚举(enhanced enum):枚举成员可以带字段与方法。
///
/// 对照 Go 的 `iota` + 手写 `String()`;Dart 的枚举是真正的类型,还能被 switch 穷尽检查。
enum Planet {
  mercury(massKg: 3.30e23, radiusKm: 2440),
  earth(massKg: 5.97e24, radiusKm: 6371),
  mars(massKg: 6.42e23, radiusKm: 3390);

  const Planet({required this.massKg, required this.radiusKm});

  final double massKg;
  final double radiusKm;

  /// 表面重力 g = GM/r²,G = 6.674e-11
  double get surfaceGravity =>
      6.674e-11 * massKg / ((radiusKm * 1000) * (radiusKm * 1000));

  /// 枚举的 `name` / `index` 是内置的,不需要手写映射表。
  String get label => '$name (${index + 1}/${values.length})';
}

代码构成:dart 27 KB · text 11 KB · yaml 400 B

本地运行

zip → 解压 → 执行
$cd examples/ch03-types-collections && dart pub get && dart run

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • dart analyze(0 告警)、dart test(32 个用例全绿)
查看全部示例