How to Replicate a Do While Loop in Go?

DDD
Release: 2024-11-20 03:23:01
Original
209 people have browsed it

How to Replicate a Do While Loop in Go?

Replication of Do While Loop in Go

In Go, the concept of a while loop does not directly correlate to Java's do while loop. However, there are ways to emulate the functionality of a do while loop using other loop structures available in Go.

Let's delve into the code sample you provided:

var i = 1
for i > 0 {
    fmt.Println("Press 1 to run")
    fmt.Println("Press 2 to exit")
    var input string
    inpt, _ := fmt.Scanln(&input)
    switch inpt {
    case 1:
        fmt.Println("hi")
    case 2:
        os.Exit(2)
    default:
        fmt.Println("def")
    }
}
Copy after login

Your code is locked in an infinite loop irrespective of the input because the loop condition i > 0 is always true. To emulate do while behavior, you need to use a different loop structure that checks the loop condition only after the loop body has been executed.

Here's a modified version of your code that achieves the desired functionality:

var input int
for {
    fmt.Println("Press 1 to run")
    fmt.Println("Press 2 to exit")
    n, err := fmt.Scanln(&input)
    if n < 1 || err != nil {
        fmt.Println("Invalid input")
        break
    }

    switch input {
    case 1:
        fmt.Println("hi")
    case 2:
        fmt.Println("Exiting...")
        return
    default:
        fmt.Println("Invalid input")
    }
}
Copy after login

In this code:

  • The loop variable i is removed, and a new variable input of type int is used to capture user input.
  • The loop condition is not defined, which results in an infinite loop.
  • The break statement is used to exit the loop when the user enters an invalid input or chooses to exit.
  • The return statement is used to exit the function when the user chooses to exit, effectively terminating the program.

This code provides the desired behavior of executing the loop body until the user explicitly chooses to exit.

The above is the detailed content of How to Replicate 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template