简体   繁体   中英

How do I run a function until the expected value is returned?

I want to run a function until it returns 0.

value, _ := FuncX()

if value != 0 {
                    value, _ := FuncX()
                  if(value != 0) {
                     value, _ := FuncX()
                      if(value != 0) ....
                  }
}

seems like a pretty ugly way to do it. Whats a possible better way?

A more complex loop header than others have offered, although having nothing in the loop body may trigger coder OCD.

for value,_ := FuncX(); value != 0; value,_ = FuncX() {
}

In fact, this is usually how I read files line by line in Go

// Assume we have some bufio.Reader named buf already created
for line,err := buf.ReadString('\n'); err == nil; line,err = buf.ReadString('\n') {
    // Do stuff with the line.
}

If you need line or err outside the loop you just predeclare them and replace the := with = .

for {
    value, _ := FuncX()
    if value == 0 {
        break
    }
}

You can use a loop like:

value, _ := FuncX()
for value == 0 {
    value, _ = FuncX() // note using the = not :=
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM