DartCH 01ch01_dart_basics
ch01-dart-basics
Dart 起步:值与变量、函数、基础类型、const/final。完整工程共 6 个文件,其中 6 个文本源文件可在下面在线阅读。
6
在线文本文件
824
源码行数
dart / yaml / text
语言
11 KB
打包体积
在线阅读源码
左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。
darttextyaml
6 text files · 824 lines
dartlib/basics.dart175 行 · 8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/// 第 1 章 · Dart 起步:值与变量、函数、基础类型、`const`/`final`。
///
/// 每个函数对应正文里的一个小节,返回值都能被 `test/basics_test.dart` 断言。
/// 代码刻意与 C / Go 的写法并排对照,读者可以带着"如果是 C/Go 会怎么写"的问题读。
library;
// ===========================================================================
// 1. 数字:int / double / num
// ===========================================================================
/// Dart 原生(VM / AOT)的 `int` 是**定长 64 位有符号整数**,溢出静默回绕。
///
/// 对照 C:`int64_t` 溢出是未定义行为(UB),而 Dart 明确规范为二进制补码回绕;
/// 对照 Go:完全一致(Go 的 int64 也是回绕)。
int intOverflow() => 9223372036854775807 + 1; // -9223372036854775808
/// `~/` 是向零截断的整除(等价于 C 的 `/`);`/` 永远返回 `double`。
///
/// 陷阱:`7 / 2` 在 Dart 里是 `3.5`,不是 `3`。Go 程序员常在这里写错类型。
int truncatingDivision(int a, int b) => a ~/ b;
/// `%` 是**欧几里得取模**:结果永远非负。这与 C / Go / Python 都不同。
///
/// C99/Go: `-7 % 3 == -1`(符号跟随被除数);Python: `-7 % 3 == 2`、`7 % -3 == -2`(跟随除数);
/// Dart: `(-7) % 3 == 2` **且** `7 % -3 == 1`。想要 C 语义就用 `remainder()`。
int cStyleRemainder(int a, int b) => a.remainder(b);
int moduloFollowsDivisor(int a, int b) => a % b;
/// `/` 的结果是双精度浮点,与 C 的 `/`(操作数为 int 时)语义不同。
double doubleDivision(int a, int b) => a / b;
/// 0.1 + 0.2 != 0.3,IEEE-754 的坑在三种语言里一模一样。
bool floatSumIsExact() => 0.1 + 0.2 == 0.3;
/// `num` 是 `int` 与 `double` 的公共父类型,类似 Go 里"接口装着 int64 或 float64"。
num absOf(num x) => x.abs();
/// 字面量支持十六进制与科学计数,但没有 `L`/`u` 后缀。
///
/// 陷阱:Dart **没有二进制字面量**(C 的 `0b1010`、Go 的 `0b1010` 在 Dart 里是语法错误),
/// 要用 `int.parse('1010', radix: 2)`。
int hexLiteral() => 0xFF + 0x0A; // 255 + 10
// ===========================================================================
// 2. 字符串:String 是 UTF-16 码元的不可变序列
// ===========================================================================
/// 字符串插值:`$expr` 或 `${expr}`,比 C 的 `printf` 更安全(编译期检查类型)。
String greet(String name, int age) => 'Hello, $name (${age + 1} next year)';
/// 原始字符串(raw string):反斜杠不转义,写 Windows 路径和正则时必备。
String windowsPath() => r'C:\temp\new\file.txt';
/// 多行字符串,保留换行。
String banner() => '''
=== Dart 起步 ===
''';
/// `length` 是 **UTF-16 码元**个数,不是字符数(1 个 emoji 可能占 2)。
/// 这与 Go 的 `len(s)`(字节数)一样"不是你以为的那个长度"。
int codeUnitLength(String s) => s.length;
/// `runes` 才是 Unicode 码点序列;Go 里对应 `[]rune(s)`。
int runeLength(String s) => s.runes.length;
// ===========================================================================
// 3. const / final / var:三种"不可变"层次
// ===========================================================================
/// `const`:**编译期**常量,类似 C 的 `#define` / `static const`、Go 的 `const`。
/// 只能被字面量或其它 const 表达式初始化。
const int maxRetries = 3;
/// `const` 集合:不仅不可变,而且相同内容会被**规范化(canonicalize)**为同一对象。
const List<int> defaultPorts = [80, 443];
/// `final`:运行期"只赋值一次",类似 C 里 `Type *const p`、Go 里没有对应物(Go 只有 const)。
/// 每次执行到这里都会产生新对象。
DateTime requestTimestamp() => DateTime.now();
/// 两个内容相同的 `const` 列表,是**同一个对象**。
bool constListsAreCanonicalized() => identical(defaultPorts, const [80, 443]);
/// 内容相同的 `final`/普通列表,是**两个不同对象**,且 `==` 也不相等(没有结构相等)。
bool plainListsAreNotEqual() => <int>[80, 443] == <int>[80, 443]; // false
// ===========================================================================
// 4. 函数:命名参数、可选位置参数、没有重载
// ===========================================================================
/// Dart 没有函数重载(没有 C++/Java 那套 name mangling),
/// 用**可选命名参数 + 默认值**代替 Go 里那堆 `WithXXX` 选项函数。
String buildUser({
required String name,
int age = 0,
String tag = 'default',
bool active = true,
}) =>
'User(name: $name, age: $age, tag: $tag, active: $active)';
/// 可选**位置**参数(`[]` 包裹),类似 Go 的可变参但只能省略尾部。
int sumAll(List<int> xs, [int start = 0]) =>
xs.fold(start, (int acc, int x) => acc + x);
/// 可变参数:`...` 是"展开(spread)",不是 Go 的 `xs...`。
int sumSpread(List<int> a, List<int> b) =>
sumAll(<int>[...a, ...b]);
// ===========================================================================
// 5. 函数是一等公民:函数类型、tear-off、闭包
// ===========================================================================
/// `typedef` 给函数类型起名,类似 C 的 `typedef int (*op)(int, int)`。
typedef IntBinOp = int Function(int a, int b);
int add(int a, int b) => a + b;
int mul(int a, int b) => a * b;
/// 把函数当值传,对应 C 的函数指针参数。
int applyOp(IntBinOp op, int a, int b) => op(a, b);
/// 方法是 tear-off:`applyOp(add, ...)` 直接把顶层函数当值用,不用取地址 `&add`。
int addThenMul(int a, int b) => applyOp(add, a, b) * 2;
/// 闭包捕获的是**变量本身**,生命周期由 GC 延长(相当于闭包替你 `malloc` + 不 `free`)。
///
/// 对照 C:这里要么手写 struct + 函数指针,要么接受"变量随栈帧消失"的 bug。
int Function(int delta) makeAccumulator({int start = 0}) {
var total = start; // 被闭包捕获的局部变量,逃逸到堆上
return (int delta) => total += delta;
}
/// `for (var i = ...)` 的循环变量是**每轮迭代新建**的,
/// 所以每个闭包捕获到的是各自那一轮的 `i`(0,1,2)。
/// Dart 从一开始就这样;Go 直到 1.22 才改成同样的语义。
List<int> capturedLoopVariables(int n) {
final fns = <int Function()>[];
for (var i = 0; i < n; i++) {
fns.add(() => i);
}
return fns.map((int Function() f) => f()).toList();
}
// ===========================================================================
// 6. record:值语义的轻量元组(最像 Go 的多返回值)
// ===========================================================================
/// Go 用多返回值 `(q, r)`;Dart 用 record。record 是**值对象**,按字段比较相等。
({int quotient, int remainder}) divMod(int a, int b) =>
(quotient: a ~/ b, remainder: a % b);
/// 位置记录(无名),适合临时两个值。
(int, int) minMax(List<int> xs) {
var lo = xs.first, hi = xs.first;
for (final x in xs) {
if (x < lo) lo = x;
if (x > hi) hi = x;
}
return (lo, hi);
}
// ===========================================================================
// 7. 静态类型与 dynamic
// ===========================================================================
/// `var` 让编译器推断类型;一旦推断出来就**钉死**(不是 C 的 auto 那种静态类型?——其实是一样的)。
String inferredTypeOf(int x) => 'x 的类型是 ${x.runtimeType}';
/// `dynamic` 关闭静态检查,运行时才查:相当于 C 的 `void*` + 强制转换、Go 的 `interface{}`。
/// 用它就意味着放弃了编译器帮你找 bug,生产代码里应尽量避免。
String dynamicDispatch(dynamic value) {
// 运行时才知道 value 有没有这个方法;写错名字 → 运行期 NoSuchMethodError。
return value.toString();
}
代码构成:dart 15 KB · text 11 KB · yaml 379 B
本地运行
zip → 解压 → 执行$cd examples/ch01-dart-basics && dart pub get && dart run这个 zip 里有什么
- • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
- • lib / bin / test / native 全部源码与测试
- • pubspec.yaml、锁文件与平台配置文件
- • 已排除 .dart_tool / build / target / ephemeral 等构建产物
已验证
- dart analyze(0 告警)、dart test(25 个用例全绿)