我試圖在飛鏢中做這件事,但它失敗了,我真的不明白為什么。我知道 dart 不像 elixir 那樣支持強大的“模式匹配”,但我認為它應該能夠比較兩個串列。不,為什么不呢?不能等同于兩個串列的打字系統是什么?如果可以,它甚至可以支持基本的模式匹配嗎?我只是想了解 equate 在 dart 中的作業原理。
void main() {
final x = 1;
final y = 2;
if (x == 1 && y == 2) {
print('this works fine of course');
}
if ([1, 2] == [1, 2]) {
print('but this does not');
}
if ([x, y] == [1, 2]) {
print('would this work if dart could equate lists?');
}
}
uj5u.com熱心網友回復:
Dart 串列沒有operator==以檢查元素是否相等的方式實作。Dart 串列被假定為可變的,并且 Dart 平臺庫通常不為可變物件提供相等性,因為它們不能保證隨著時間的推移保持這種相等性。此外,對于串列,因為使用哪個相等并不明顯。它應該只比較元素嗎?那么一個<num>[1]串列將等于<int>[1],即使它們是非常不同的串列。
由于這些原因,你應該決定你真正想要的平等,而不是規范的平等。
例如,您可以使用const ListEquality().equalsfrom package:collection。它默認==在元素上使用,但也可以配置為使用其他等式。
uj5u.com熱心網友回復:
import 'package:flutter/foundation.dart';
void main() async {
final x = 1;
final y = 2;
if (x == 1 && y == 2) {
print('this works fine of course');
}
if (listEquals([1, 2],[1, 2])) {
print('Yep');
}
if (listEquals([x, y], [1, 2])) {
print('would this work if dart could equate lists? Yep');
}
}
輸出:
this works fine of course
Yep
would this work if dart could equate lists? Yep
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/524110.html
標籤:镖模式匹配
上一篇:Flutter、CloudFirestore和Provider:獲取資料
下一篇:將位元組寫入特定偏移量的檔案
