Home > Backend Development > Golang > How Can You Emulate a Do While Loop in Go?

How Can You Emulate a Do While Loop in Go?

Mary-Kate Olsen
Release: 2024-11-13 13:40:02
Original
363 people have browsed it

How Can You Emulate a Do While Loop in Go?

Replicating do while Loops in Go

In Go, there is no direct equivalent to the do while loop found in many other programming languages. However, there are ways to achieve similar functionality. One method is to use a for loop with a boolean loop variable initialized to true.

The following code demonstrates how to emulate a do while loop in Go:

for ok := true; ok; ok = EXPR {
  // Code to be executed
}
Copy after login

This loop will continue to execute the code block until the expression EXPR evaluates to false. In the context of the original problem, this expression would be whether the user input matches a desired exit condition.

Here is a modified version of the provided code that correctly implements the desired functionality:

func sample() {
  for ok := true; ok; ok = (input != 2) {
    fmt.Println("Press 1 to run")
    fmt.Println("Press 2 to exit")
    var input int
    fmt.Scanln(&input)

    switch input {
    case 1:
      fmt.Println("hi")
    case 2:
      // Exit the program
      os.Exit(2)
    default:
      fmt.Println("def")
    }
  }
}
Copy after login

In this code, the loop continues until the user inputs 2 (to exit). If the input is 1, it executes the "hi" statement. If the input is anything else, it executes the "def" statement.

Note that you can replace os.Exit(2) with an explicit call to return to exit the function early.

The above is the detailed content of How Can You Emulate a Do While Loop in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template