Home > Backend Development > Golang > Does Go Utilize Short Circuit Evaluation in Boolean Expressions?

Does Go Utilize Short Circuit Evaluation in Boolean Expressions?

Linda Hamilton
Release: 2024-11-08 13:51:02
Original
1076 people have browsed it

Does Go Utilize Short Circuit Evaluation in Boolean Expressions?

Does Go Implement Short Circuit Evaluation?

Short circuit evaluation refers to the practice of only evaluating an expression in an if statement if it is necessary to determine the result of the statement. In other words, if the first expression in an if statement evaluates to false, the remaining expressions are not evaluated.

Go does implement short circuit evaluation. This can be illustrated with the following code:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if testFunc(1) || testFunc(2) {
            // do nothing
        }
    }
}

func testFunc(i int) bool {
    fmt.Printf("function %d called\n", i)
    return true
}
Copy after login

When this code is executed, it will print the following output:

$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
$ function 1 called
Copy after login

As you can see, the function testFunc(2) is never called, because the first expression in the if statement (testFunc(1)) evaluates to true. This demonstrates that Go implements short circuit evaluation.

The above is the detailed content of Does Go Utilize Short Circuit Evaluation in Boolean Expressions?. 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