[Dart翻译]Dart中的label

619 阅读1分钟

原文地址:www.geeksforgeeks.org/labels-in-d…

原文作者:

发布时间:2020年5月11日

大多数使用C语言编程的人,都知道goto和标签语句是用来从一个点跳到另一个点的,但与Java不同的是,Dart也没有任何goto语句,但实际上它有标签,可以与continue和break语句一起使用,帮助他们在代码中实现更大的飞跃。

必须注意的是,"label-name "和循环控制语句之间是不允许换行的。

例子#1:在break语句中使用标签

void main() {   
  
  // Definig the label 
  Geek1:for(int i=0; i<3; i++) 
  { 
    if(i < 2) 
    { 
      print("You are inside the loop Geek"); 
  
      // breaking with label 
      break Geek1; 
    } 
    print("You are still inside the loop"); 
  } 
} 

输出。

You are inside the loop Geek

上述代码的结果是只打印了一次语句,因为一旦循环被打破,就不会再进入循环。

例子#2:使用标签与continue语句一起使用

void main() {   
  
  // Definig the label 
  Geek1:for(int i=0; i<3; i++) 
  { 
    if(i < 2) 
    { 
      print("You are inside the loop Geek"); 
  
      // Continue with label 
      continue Geek1; 
    } 
    print("You are still inside the loop"); 
  } 
} 

输出。

You are inside the loop Geek
You are inside the loop Geek
You are still inside the loop

上面的代码导致打印了两次语句,因为它没有突破循环的条件,因此打印了两次。


通过www.DeepL.com/Translator(免费版)翻译