One place for hosting & domains

      Continue

      Usar instrucciones break y continue cuando se trabaja con bucles en Go


      Introducción

      Usar bucles for en Go le permite automatizar y repetir tareas de forma eficiente.

      Aprender a controlar el funcionamiento y el flujo de los bucles hará posible una lógica personalizada en su programa. Puede controlar sus bucles con las instrucciones break y continue.

      Instrucción break

      En Go, la instrucción break finaliza la ejecución del bucle actual. Una instrucción break casi siempre se sincroniza con una instrucción condicional if.

      Veamos un ejemplo en el que se utiliza la instrucción break en un bucle for:

      break.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Breaking out of loop")
                  break // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      Este pequeño programa crea un bucle for que se iterará mientras i sea inferior a 10.

      En el bucle for, hay una instrucción if. La instrucción if prueba la condición de i para ver si el valor es inferior a 5. Si el valor de i no es igual a 5, el bucle continúa e imprime el valor de i. Si el valor de i es igual a 5, el bucle ejecuta la instrucción break, imprime Breaking out of loop y deja de ejecutarse. Al final del programa, imprimimos Exiting program para indicar que cerramos el bucle.

      Cuando ejecutemos este código, el resultado será el siguiente:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Breaking out of loop Exiting program

      Esto muestra que una vez que se evalúa el entero i como equivalente a 5, el bucle se rompe porque se indica al programa que lo haga con la instrucción break.

      Bucles anidados

      Es importante recordar que la instrucción break solo detendrá la ejecución del bucle más interno en el que se invoca. Si tiene un conjunto de bucles anidados, necesitará una instrucción break para cada bucle, si lo desea.

      nested.go

      package main
      
      import "fmt"
      
      func main() {
          for outer := 0; outer < 5; outer++ {
              if outer == 3 {
                  fmt.Println("Breaking out of outer loop")
                  break // break here
              }
              fmt.Println("The value of outer is", outer)
              for inner := 0; inner < 5; inner++ {
                  if inner == 2 {
                      fmt.Println("Breaking out of inner loop")
                      break // break here
                  }
                  fmt.Println("The value of inner is", inner)
              }
          }
          fmt.Println("Exiting program")
      }
      

      En este programa, hay dos bucles. Aunque ambos bucles se repiten 5 veces, cada uno tiene una instrucción if condicional con una instrucción break. El bucle externo se interrumpirá si el valor de outer es igual a 3. El bucle interno se interrumpirá si el valor de inner es 2.

      Si ejecutamos el programa, veremos el siguiente resultado:

      Output

      The value of outer is 0 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 1 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 2 The value of inner is 0 The value of inner is 1 Breaking out of inner loop Breaking out of outer loop Exiting program

      Observe que cada vez que se interrumpe el bucle interno, no sucede lo mismo con el externo. Esto es porque break solo interrumpirá el bucle más interno desde el que se invoca.

      Hemos visto cómo el uso de break detendrá la ejecución de un bucle. A continuación, veremos la forma de continuar la iteración de un bucle.

      Instrucción continue

      La instrucción continue se usa cuando se busca omitir la parte restante del bucle, volver a la parte superior de este y continuar con una nueva iteración.

      Como en el caso de la instrucción break, la instrucción continue se utiliza comúnmente con una instrucción if condicional.

      Usando el mismo programa de bucle for que en la sección Instrucción break, emplearemos la instrucción continue en vez de break:

      continue.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Continuing loop")
                  continue // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      La diferencia al usar la instrucción continue en vez de una instrucción break radica en que nuestro código continuará a pesar de la interrupción cuando la variable i se evalúe como equivalente a 5. Veamos el resultado:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Continuing loop The value of i is 6 The value of i is 7 The value of i is 8 The value of i is 9 Exiting program

      Aquí vemos que la línea The value of i is 5 nunca se aparece en el resultado, pero el bucle continúa después de ese punto para imprimir líneas para los números 6 a 10 antes de cerrarse.

      Puede usar la instrucción continue para evitar código condicional profundamente anidado o para optimizar un bucle eliminando los casos frecuentes que desee rechazar.

      La instrucción continue hace que un programa omita determinados factores que surgen dentro de un bucle, pero luego continuará con resto de este.

      Conclusión

      Las instrucciones break y continue en Go le permitirán usar los bucles for de forma más eficaz en su código.



      Source link

      Использование выражений Break и Continue при работе с циклами в Go


      Введение

      Использование циклов for в Go позволяет эффективно автоматизировать и повторять выполнение задач.

      Понимание принципов контроля и работы циклов позволяет использовать в программе персонализированную логику. Вы можете контролировать циклы с помощью выражений break и continue.

      Оператор Break

      В языке Go оператор break останавливает выполнение текущего цикла. Выражение break почти всегда сочетается с условным выражением if.

      Рассмотрим пример использования выражения break в цикле for:

      break.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Breaking out of loop")
                  break // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      Эта небольшая программа создает цикл for, выполняющийся пока i меньше 10.

      В цикле for содержится выражение if. Выражение if проверяет условие i и сравнивает значение с 5. Если значение i не равно 5, цикл продолжается и распечатывает значение i. Если значение i равно 5, цикл выполняет выражение break, печатает сообщение о выходе из цикла Breaking out of loop и останавливает выполнение цикла. После окончания выполнения программы распечатывается сообщение Exiting program, показывающее, что мы выполнили выход из цикла.

      При выполнении этого кода результат будет выглядеть следующим образом:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Breaking out of loop Exiting program

      Это показывает, что когда целое число i оценивается как равное 5, цикл прекращается, о чем программу информирует выражение break.

      Вложенные циклы

      Важно отметить, что выражение break останавливает выполнение только цикла самого низкого выполняемого уровня. Если вы используете набор из нескольких циклов, вложенных друг в друга, вам нужно будет использовать отдельный оператор break для каждого цикла.

      nested.go

      package main
      
      import "fmt"
      
      func main() {
          for outer := 0; outer < 5; outer++ {
              if outer == 3 {
                  fmt.Println("Breaking out of outer loop")
                  break // break here
              }
              fmt.Println("The value of outer is", outer)
              for inner := 0; inner < 5; inner++ {
                  if inner == 2 {
                      fmt.Println("Breaking out of inner loop")
                      break // break here
                  }
                  fmt.Println("The value of inner is", inner)
              }
          }
          fmt.Println("Exiting program")
      }
      

      Эта программа содержит два цикла. Хотя оба цикла выполняют 5 итераций, в каждом из них есть условное выражение if с выражением break. Внешний цикл прекращается, если значение outer равняется 3. Внутренний цикл прекращается, если значение inner равняется 2.

      Если мы запустим программу, результат будет выглядеть следующим образом:

      Output

      The value of outer is 0 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 1 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 2 The value of inner is 0 The value of inner is 1 Breaking out of inner loop Breaking out of outer loop Exiting program

      Обратите внимание, что при остановке внутреннего цикла внешний цикл не останавливается. Это связано с тем, что выражение break останавливает только цикл самого низкого уровня, где оно вызывается.

      Мы увидели, как выражение break останавливает выполнение цикла. Теперь посмотрим, как можно продолжить итерации цикла.

      Оператор Continue

      Выражение continue используется, когда вы хотите пропустить оставшуюся часть цикла, вернуться в начало цикла и продолжить новую итерацию этого цикла.

      Как и выражение break, выражение continue обычно используется вместе с условным выражением if.

      Мы используем ту же программу с циклом for, что и в предыдущем разделе «Выражение Break», но при этом используем выражение continue вместо выражения break:

      continue.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Continuing loop")
                  continue // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      Отличие выражения continue от выражения break заключается в том, что код продолжит выполняться несмотря на прерывание, если переменная i будет оценена как равная 5. Посмотрим на результаты:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Continuing loop The value of i is 6 The value of i is 7 The value of i is 8 The value of i is 9 Exiting program

      Здесь вы видим, что строка The value of i is 5 не появляется в результатах, но цикл продолжает выполнение после этой точки и распечатывает строки для чисел 6-10 перед остановкой цикла.

      Вы можете использовать выражение continue, чтобы избежать использования глубоко вложенного условного кода, или чтобы оптимизировать цикл, устранив часто встречающиеся случаи, которые вы хотите отклонять.

      Выражение continue заставляет программу пропустить определенную часть цикла, а затем продолжить выполнение оставшейся части цикла.

      Заключение

      Выражения break и continue в Go позволят вам более эффективно использовать циклы for в программном коде.



      Source link

      Using Break and Continue Statements When Working with Loops in Go


      Introduction

      Using for loops in Go allow you to automate and repeat tasks in an efficient manner.

      Learning how to control the operation and flow of loops will allow for customized logic in your program. You can control your loops with the break and continue statements.

      Break Statement

      In Go, the break statement terminates execution of the current loop. A break is almost always paired with a conditional if statement.

      Let’s look at an example that uses the break statement in a for loop:

      break.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Breaking out of loop")
                  break // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      This small program creates a for loop that will iterate while i is less than 10.

      Within the for loop, there is an if statement. The if statement tests the condition of i to see if the value is less than 5. If the value of i is not equal to 5, the loop continues and prints out the value of i. If the value of i is equal to 5, the loop will execute the break statement, print that it is Breaking out of loop, and stop executing the loop. At the end of the program we print out Exiting program to signify that we have exited the loop.

      When we run this code, our output will be the following:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Breaking out of loop Exiting program

      This shows that once the integer i is evaluated as equivalent to 5, the loop breaks, as the program is told to do so with the break statement.

      Nested Loops

      It is important to remember that the break statement will only stop the execution of the inner most loop it is called in. If you have a nested set of loops, you will need a break for each loop if desired.

      nested.go

      package main
      
      import "fmt"
      
      func main() {
          for outer := 0; outer < 5; outer++ {
              if outer == 3 {
                  fmt.Println("Breaking out of outer loop")
                  break // break here
              }
              fmt.Println("The value of outer is", outer)
              for inner := 0; inner < 5; inner++ {
                  if inner == 2 {
                      fmt.Println("Breaking out of inner loop")
                      break // break here
                  }
                  fmt.Println("The value of inner is", inner)
              }
          }
          fmt.Println("Exiting program")
      }
      

      In this program, we have two loops. While both loops iterate 5 times, each has a conditional if statement with a break statement. The outer loop will break if the value of outer equals 3. The inner loop will break if the value of inner is 2.

      If we run the program, we can see the output:

      Output

      The value of outer is 0 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 1 The value of inner is 0 The value of inner is 1 Breaking out of inner loop The value of outer is 2 The value of inner is 0 The value of inner is 1 Breaking out of inner loop Breaking out of outer loop Exiting program

      Notice that each time the inner loop breaks, the outer loop does not break. This is because break will only break the inner most loop it is called from.

      We have seen how using break will stop the execution of a loop. Next, let’s look at how we can continue the iteration of a loop.

      Continue Statement

      The continue statement is used when you want to skip the remaining portion of the loop, and return to the top of the loop and continue a new iteration.

      As with the break statement, the continue statement is commonly used with a conditional if statement.

      Using the same for loop program as in the preceding Break Statement section, we’ll use a continue statement rather than a break statement:

      continue.go

      package main
      
      import "fmt"
      
      func main() {
          for i := 0; i < 10; i++ {
              if i == 5 {
                  fmt.Println("Continuing loop")
                  continue // break here
              }
              fmt.Println("The value of i is", i)
          }
          fmt.Println("Exiting program")
      }
      

      The difference in using the continue statement rather than a break statement is that our code will continue despite the disruption when the variable i is evaluated as equivalent to 5. Let’s look at our output:

      Output

      The value of i is 0 The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4 Continuing loop The value of i is 6 The value of i is 7 The value of i is 8 The value of i is 9 Exiting program

      Here we see that the line The value of i is 5 never occurs in the output, but the loop continues after that point to print lines for the numbers 6-10 before leaving the loop.

      You can use the continue statement to avoid deeply nested conditional code, or to optimize a loop by eliminating frequently occurring cases that you would like to reject.

      The continue statement causes a program to skip certain factors that come up within a loop, but then continue through the rest of the loop.

      Conclusion

      The break and continue statements in Go will allow you to use for loops more effectively in your code.



      Source link