示例工程 ch03-types-collections
ch03-types-collections/lib/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})';
}