跳到主要内容

模式

模式是 Dart 语言中的一个语法类别,就像语句和表达式一样。模式表示它可能与实际值匹配的一组值的“形状”。

本页描述了

  • 模式的作用。
  • Dart 代码中允许出现模式的位置。
  • 模式的常见用例是什么。

要了解不同种类的模式,请访问模式类型页面。

模式的作用

#

通常,模式可以**匹配**一个值、**解构**一个值,或两者兼而有之,具体取决于上下文和模式的形状。

首先,*模式匹配*允许您检查给定值是否

  • 具有某种形状。
  • 是某个常量。
  • 等于其他值。
  • 具有某种类型。

然后,*模式解构*为您提供了一种方便的声明式语法,可以将该值分解为构成部分。同一模式还可以让您在此过程中将变量绑定到这些部分的全部或部分。

匹配

#

模式总是对值进行测试,以确定该值是否具有您期望的形式。换句话说,您正在检查该值是否*匹配*该模式。

什么构成匹配取决于您正在使用的模式类型。例如,如果值等于模式的常量,则常量模式匹配。

dart
switch (number) {
  // Constant pattern matches if 1 == number.
  case 1:
    print('one');
}

许多模式都使用子模式,有时分别称为*外部*和*内部*模式。模式对其子模式进行递归匹配。例如,任何集合类型模式的各个字段都可以是变量模式常量模式

dart
const a = 'a';
const b = 'b';
switch (obj) {
  // List pattern [a, b] matches obj first if obj is a list with two fields,
  // then if its fields match the constant subpatterns 'a' and 'b'.
  case [a, b]:
    print('$a, $b');
}

要忽略匹配值的部分,您可以使用通配符模式作为占位符。对于列表模式,您可以使用其余元素

解构

#

当一个对象和模式匹配时,模式可以访问对象的数据并将其部分提取出来。换句话说,模式*解构*对象。

dart
var numList = [1, 2, 3];
// List pattern [a, b, c] destructures the three elements from numList...
var [a, b, c] = numList;
// ...and assigns them to new variables.
print(a + b + c);

您可以在解构模式中嵌套任何类型的模式。例如,此 case 模式匹配并解构一个双元素列表,其第一个元素是 'a''b'

dart
switch (list) {
  case ['a' || 'b', var c]:
    print(c);
}

模式可出现的位置

#

您可以在 Dart 语言中的几个地方使用模式:

本节描述了使用模式进行匹配和解构的常见用例。

变量声明

#

您可以在 Dart 允许局部变量声明的任何位置使用*模式变量声明*。模式与声明右侧的值匹配。一旦匹配,它会解构该值并将其绑定到新的局部变量。

dart
// Declares new variables a, b, and c.
var (a, [b, c]) = ('str', [1, 2]);

模式变量声明必须以 varfinal 开头,后跟一个模式。

变量赋值

#

*变量赋值模式*位于赋值的左侧。首先,它解构匹配的对象。然后它将值赋给*现有*变量,而不是绑定新的变量。

使用变量赋值模式交换两个变量的值,而无需声明第三个临时变量:

dart
var (a, b) = ('left', 'right');
(b, a) = (a, b); // Swap.
print('$a $b'); // Prints "right left".

Switch 语句和表达式

#

每个 case 子句都包含一个模式。这适用于switch 语句表达式,以及if-case 语句。您可以在 case 中使用任何类型的模式

*Case 模式*是可驳回的。它们允许控制流

  • 匹配并解构被切换的对象。
  • 如果对象不匹配,则继续执行。

模式在 case 中解构的值成为局部变量。它们的作用域仅限于该 case 的主体。

dart
switch (obj) {
  // Matches if 1 == obj.
  case 1:
    print('one');

  // Matches if the value of obj is between the
  // constant values of 'first' and 'last'.
  case >= first && <= last:
    print('in range');

  // Matches if obj is a record with two fields,
  // then assigns the fields to 'a' and 'b'.
  case (var a, var b):
    print('a = $a, b = $b');

  default:
}

逻辑或模式对于在 switch 表达式或语句中让多个 case 共享一个主体很有用。

dart
var isPrimary = switch (color) {
  Color.red || Color.yellow || Color.blue => true,
  _ => false,
};

Switch 语句可以有多个 case 共享一个主体,而无需使用逻辑或模式,但它们在允许多个 case 共享一个守卫方面仍然独特有用。

dart
switch (shape) {
  case Square(size: var s) || Circle(size: var s) when s > 0:
    print('Non-empty symmetric shape');
}

守卫子句作为 case 的一部分评估任意条件,如果条件为假,则不会退出 switch(就像在 case 主体中使用 if 语句会导致)。

dart
switch (pair) {
  case (int a, int b):
    if (a > b) print('First element greater');
  // If false, prints nothing and exits the switch.
  case (int a, int b) when a > b:
    // If false, prints nothing but proceeds to next case.
    print('First element greater');
  case (int a, int b):
    print('First element not greater');
}

For 循环和 For-in 循环

#

您可以在for 和 for-in 循环中使用模式来迭代和解构集合中的值。

此示例在 for-in 循环中使用对象解构来解构 <Map>.entries 调用返回的 MapEntry 对象。

dart
Map<String, int> hist = {'a': 23, 'b': 100};

for (var MapEntry(key: key, value: count) in hist.entries) {
  print('$key occurred $count times');
}

对象模式检查 hist.entries 是否具有命名类型 MapEntry,然后递归到命名字段子模式 keyvalue。它在每次迭代中调用 MapEntry 上的 key getter 和 value getter,并将结果分别绑定到局部变量 keycount

将 getter 调用的结果绑定到同名变量是一种常见用例,因此对象模式也可以从变量子模式推断 getter 名称。这允许您将变量模式从冗余的 key: key 简化为只写 :key

dart
for (var MapEntry(:key, value: count) in hist.entries) {
  print('$key occurred $count times');
}

模式用例

#

上一节描述了模式如何融入其他 Dart 代码构造。您看到了一些有趣的用例作为示例,例如交换两个变量的值,或者解构 Map 中的键值对。本节描述了更多用例,回答了:

  • 您何时以及为何可能想使用模式。
  • 它们解决了哪些类型的问题。
  • 它们最适合哪些惯用法。

解构多返回值

#

记录允许聚合并从单个函数调用返回多个值。模式增加了直接将记录的字段解构到局部变量中的能力,与函数调用内联。

无需为每个记录字段单独声明新的局部变量,像这样:

dart
var info = userInfo(json);
var name = info.$1;
var age = info.$2;

您可以使用变量声明赋值模式以及记录模式作为其子模式,将函数返回的记录字段解构到局部变量中。

dart
var (name, age) = userInfo(json);

要使用模式解构带命名字段的记录:

dart
final (:name, :age) =
    getData(); // For example, return (name: 'doug', age: 25);

解构类实例

#

对象模式匹配命名对象类型,允许您使用对象类已公开的 getter 来解构其数据。

要解构类的实例,请使用命名类型,后跟括号中要解构的属性:

dart
final Foo myFoo = Foo(one: 'one', two: 2);
var Foo(:one, :two) = myFoo;
print('one $one, two $two');

代数数据类型

#

对象解构和 switch-case 有助于编写代数数据类型风格的代码。在以下情况使用此方法:

  • 您有一系列相关类型。
  • 您有一个操作,需要针对每种类型进行特定行为。
  • 您希望将该行为集中在一处,而不是分散到所有不同的类型定义中。

无需为每种类型实现操作作为实例方法,而是将操作的变体保留在一个函数中,该函数切换子类型:

dart
sealed class Shape {}

class Square implements Shape {
  final double length;
  Square(this.length);
}

class Circle implements Shape {
  final double radius;
  Circle(this.radius);
}

double calculateArea(Shape shape) => switch (shape) {
  Square(length: var l) => l * l,
  Circle(radius: var r) => math.pi * r * r,
};

验证传入的 JSON

#

Maplist 模式非常适合解构反序列化数据中的键值对,例如从 JSON 解析的数据。

dart
var data = {
  'user': ['Lily', 13],
};
var {'user': [name, age]} = data;

如果您知道 JSON 数据具有您期望的结构,那么前面的示例是现实的。但数据通常来自外部源,例如通过网络。您需要先验证它以确认其结构。

没有模式,验证会很冗长:

dart
if (data is Map<String, Object?> &&
    data.length == 1 &&
    data.containsKey('user')) {
  var user = data['user'];
  if (user is List<Object> &&
      user.length == 2 &&
      user[0] is String &&
      user[1] is int) {
    var name = user[0] as String;
    var age = user[1] as int;
    print('User $name is $age years old.');
  }
}

单个case 模式可以实现相同的验证。单个 case 最适合作为if-case 语句。模式提供了一种更具声明性且更简洁的 JSON 验证方法:

dart
if (data case {'user': [String name, int age]}) {
  print('User $name is $age years old.');
}

此 case 模式同时验证:

  • json 是一个 Map,因为它必须首先匹配外部Map 模式才能继续。
    • 而且,由于它是一个 Map,它也确认 json 不为 null。
  • json 包含一个键 user
  • user 与两个值的列表配对。
  • 列表值的类型是 Stringint
  • 用于保存值的新局部变量是 nameage