英文:
Switch statement in dart with set expression
问题
以下是翻译好的内容:
这里有一个带有switch
语句的简单的Dart程序。
void main() {
var list = [1, 2];
var set = <int>{1, 2};
var map = <int, int>{1: 2, 3: 4};
switch (list) {
case 1:
print(1);
break;
case [1, 2]:
print(2);
break;
case const <int>{1, 2}:
print(3);
break;
case <int, int>{1: 2, 3: 4}:
print(4);
break;
}
}
根据我了解,Dart语言中的switch
语句不会为每个情况检查==
,而是进行模式匹配。
在上面的代码中,当表达式是switch(list)
时,控制台打印出2
。当它是switch(set)
时,控制台不会打印任何内容,而对于switch(map)
,控制台打印出4
。
问题:
- 为什么当表达式是
switch(set)
时,switch
不打印3
? - 为什么
Set
需要const
,而List
和Map
不需要?
如果我在Set
的情况下删除const
,我会收到错误消息:
常量模式的表达式必须是有效的常量。
英文:
Here is a simple dart program with a switch statement.
void main() {
var list = [1, 2];
var set = <int>{1, 2};
var map = <int, int> {1: 2, 3: 4};
switch (list) {
case 1:
print(1);
break;
case [1, 2]:
print(2);
break;
case const <int> {1, 2}:
print(3);
break;
case <int, int>{1: 2, 3: 4}:
print(4);
break;
}
}
As I understand in the dart lang, the switch
statement does not check ==
for every case, but rather it does pattern matching.
In the above code, when the expression is switch(list)
, the console prints 2
. When it is switch(set)
, the console does not print anything, and for switch(map)
, the console prints 4
.
Questions:
- Why when the expression is
switch(set)
, the switch does not print3
? - Why
const
is required forSet
, and not forList
andMap
?
If I removeconst
in the set case, I get an error message :
>The expression of a constant pattern must be a valid constant.
答案1
得分: 0
以下是已翻译好的内容:
Dart支持以下类型的模式:
请注意,List
和 Map
都具有内置的模式类型,而 Set
则没有。
然而,还有一个常量模式,允许使用 case const <int> {1, 2}:
。
另请考虑以下内容:
void main() {
print(const <int> {1, 2} == <int> {1, 2}); // false
print(const <int> {1, 2} == const <int> {1, 2}); // true
}
因此,考虑到这一点,以下代码:
void main() {
var list = [1, 2];
var set = const <int>{1, 2}; // 添加 const
var map = <int, int> {1: 2, 3: 4};
switch (set) {
case 1:
print(1);
break;
case [1, 2]:
print(2);
break;
case const <int> {1, 2}:
print(3);
break;
case <int, int>{1: 2, 3: 4}:
print(4);
break;
}
}
会打印出 3
。
英文:
Dart supports the following types of patterns:
- Logical-or
- Logical-and
- Relational
- Cast
- Null-check
- Null-assert
- Constant
- Variable
- Identifier
- Parenthesized
- List
- Map
- Record
- Object
- Wildcard
Notice that both List
and Map
have built-in pattern types, while Set
does not.
There is however a constant pattern, which allows for case const <int> {1, 2}:
.
Also consider this:
void main() {
print(const <int> {1, 2} == <int> {1, 2}); // false
print(const <int> {1, 2} == const <int> {1, 2}); // true
}
So with that in mind, the following:
void main() {
var list = [1, 2];
var set = const <int>{1, 2}; // add const
var map = <int, int> {1: 2, 3: 4};
switch (set) {
case 1:
print(1);
break;
case [1, 2]:
print(2);
break;
case const <int> {1, 2}:
print(3);
break;
case <int, int>{1: 2, 3: 4}:
print(4);
break;
}
}
prints 3
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论