Home  >  Article  >  Backend Development  >  Can You Initialize Multiple Variables in a Go If Statement?

Can You Initialize Multiple Variables in a Go If Statement?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 19:01:01659browse

Can You Initialize Multiple Variables in a Go If Statement?

Multiple Initializers in a Go If Statement

In Go, it is possible to initialize multiple variables in an if statement. This can be useful in situations where you want to assign different values to multiple variables based on the outcome of a condition.

To initialize multiple variables in an if statement, use the following syntax:

if x, y := 5, 38; x == 5 {
    // Do something
}

In this example, x is assigned the value 5 and y is assigned the value 38. The if statement will only execute its body if x is equal to 5.

Example:

Here is a complete example of initializing multiple variables in an if statement:

<code class="go">package main

import (
    "fmt"
)

func main() {
    if x, y := 5, 38; x == 5 {
        fmt.Printf("Whee! %d\n", y)
    }
}</code>

When this program is run, it will output the following:

Whee! 38

The above is the detailed content of Can You Initialize Multiple Variables in a Go If Statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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