Home  >  Article  >  Backend Development  >  Golang function declaration syntax

Golang function declaration syntax

WBOY
WBOYOriginal
2024-04-19 16:48:02789browse

The declaration syntax of a Go function is func () { }. Among them, is the function name, is the parameter type and name, is the return value type and name, { } is the function execution code piece.

Golang function declaration syntax

Go function declaration syntax

The function declaration syntax in Go language is as follows:

func <函数名>(<参数列表>) <返回值列表> {
    // 函数体
}

Where:

  • <function name></function>: The name of the function.
  • <parameter list></parameter>: The parameter list of the function, with parameter types and names separated by commas.
  • <return value list></return>: The return value list of the function, the return value type and name are separated by commas.
  • {}: Function body, containing the code for function execution.

Practical case: Calculate the mean of two numbers

func mean(a, b int) float64 {
    return float64(a+b) / 2
}

func main() {
    s1 := mean(2, 4)
    s2 := mean(5, 10)
    fmt.Println(s1) // 输出:3
    fmt.Println(s2) // 输出:7.5
}

In this example:

  • mean The function calculates the mean of two integer parameters and returns a floating point number.
  • main The function is the entry point of the program, where:

    • Call the mean function to calculate the mean of two numbers, And store the results in s1 and s2.
    • Output the values ​​of s1 and s2.

The above is the detailed content of Golang function declaration syntax. 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