Home >Backend Development >Golang >How do you define and call functions in Go?
In Go, functions are defined using the func
keyword followed by the function name and a set of parentheses containing the parameter list. The body of the function is enclosed in curly braces {}
. Here is a basic example of a function definition:
<code class="go">func add(a int, b int) int { return a b }</code>
In this example, add
is a function that takes two parameters of type int
and returns an int
.
To call a function in Go, you simply use the function name followed by the arguments in parentheses. For example:
<code class="go">result := add(3, 4) fmt.Println(result) // Output: 7</code>
Here, add
function is called with arguments 3
and 4
, and the result is stored in the result
variable.
In Go, function naming follows certain conventions to maintain readability and consistency. Here are some best practices:
calculateAverage
.calculateAverage
rather than something cryptic like calcAvg
.calculate
is preferred over calc
.Add
is exported, while add
is not.In Go, you can pass arguments to functions using different methods, each with its own characteristics:
Value Parameters: The default way to pass arguments in Go is by value. When you pass an argument by value, a copy of the value is made and passed to the function. Changes to the parameter inside the function do not affect the original value outside the function.
<code class="go">func incrementByValue(x int) { x } a := 1 incrementByValue(a) fmt.Println(a) // Output: 1 (a remains unchanged)</code>
Pointer Parameters: You can pass a pointer to a value. This allows the function to modify the original value.
<code class="go">func incrementByPointer(x *int) { (*x) } a := 1 incrementByPointer(&a) fmt.Println(a) // Output: 2 (a is modified)</code>
Variadic Parameters: Go supports variadic functions, which can accept an indefinite number of arguments of the same type. The variadic parameter is denoted by ...
before the type.
<code class="go">func sum(numbers ...int) int { total := 0 for _, num := range numbers { total = num } return total } fmt.Println(sum(1, 2, 3, 4)) // Output: 10</code>
Return values in Go functions play a crucial role in allowing functions to communicate results back to the caller. Here are key points about return values in Go:
Single Return Value: A function can return a single value. The return type is specified after the parameter list.
<code class="go">func square(x int) int { return x * x }</code>
Multiple Return Values: Go allows functions to return multiple values. This is useful for returning both a result and an error.
<code class="go">func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } result, err := divide(10, 2) if err != nil { fmt.Println(err) } else { fmt.Println(result) // Output: 5 }</code>
Named Return Values: Go supports named return values, which can make the code more readable. Named return values are declared as part of the function signature.
<code class="go">func namedReturn(x int) (result int) { result = x * x return }</code>
Bare Return: When using named return values, Go allows the use of a bare return
statement, which returns the named return values.
<code class="go">func namedReturnWithBareReturn(x int) (result int) { result = x * x return // equivalent to return result }</code>
Return values are crucial for error handling, allowing functions to return both a result and an error status, which is a common pattern in Go programming.
The above is the detailed content of How do you define and call functions in Go?. For more information, please follow other related articles on the PHP Chinese website!