Golang function declaration syntax

WBOY
Release: 2024-04-19 16:48:02
Original
786 people have browsed it

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 <函数名>(<参数列表>) <返回值列表> {
    // 函数体
}
Copy after login

Where:

  • <Function name>: The name of the function.
  • <Parameter list>: The parameter list of the function, with parameter types and names separated by commas.
  • <Return value list>: 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
}
Copy after login

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!

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