Contents
Swift
Function Basics​
In Go, a function is defined using the func
keyword, followed by the function name, parameters, return type, and the function body. Here is a basic example:
package main
import "fmt"
// Function that takes two integers and returns their sum
func add(x int, y int) int {
return x + y
}
func main() {
result := add(3, 4)
fmt.Println("Sum:", result) // Output: Sum: 7
}
Multiple Return Values
One of the powerful features of Go is the ability to return multiple values from a function. This is particularly useful for returning error information alongside regular data.
package main
import (
"fmt"
"strconv"
)
// Function that converts a string to an integer and returns the result and an error if any
func stringToInt(s string) (int, error) {
num, err := strconv.Atoi(s)
return num, err
}
func main() {
// Convert a valid string
num, err := stringToInt("42")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Number:", num) // Output: Number: 42
}
// Convert an invalid string
num, err = stringToInt("invalid")
if err != nil {
fmt.Println("Error:", err) // Output: Error: strconv.Atoi: parsing "invalid": invalid syntax
} else {
fmt.Println("Number:", num)
}
}
Named Return Values
Go allows you to name the return values of a function. This can make the code more readable and allow for cleaner handling of the function’s exit points.
package main
import "fmt"
// Function with named return values
func divide(x, y float64) (result float64, err error) {
if y == 0 {
err = fmt.Errorf("cannot divide by zero")
return // implicitly returns result (0.0) and err
}
result = x / y
return // implicitly returns result and err (nil)
}
func main() {
// Perform division
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result) // Output: Result: 5
}
// Attempt division by zero
result, err = divide(10, 0)
if err != nil {
fmt.Println("Error:", err) // Output: Error: cannot divide by zero
} else {
fmt.Println("Result:", result)
}
}
Variadic Functions
Variadic functions can accept a variable number of arguments. This is useful for functions that need to handle lists of inputs, such as summing numbers or joining strings.
package main
import "fmt"
// Variadic function that sums numbers
func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
func main() {
// Call variadic function with different numbers of arguments
fmt.Println("Sum 1:", sum(1, 2, 3)) // Output: Sum 1: 6
fmt.Println("Sum 2:", sum(10, 20, 30, 40, 50)) // Output: Sum 2: 150
}
Anonymous Functions
Anonymous functions are functions without a name. They are useful for short, simple functions that are used only in a specific context. Anonymous functions can be defined and invoked in place or assigned to variables for reuse.
Anonymous Function Example
package main
import "fmt"
func main() {
// Define and immediately invoke an anonymous function
func() {
fmt.Println("Hello from anonymous function!")
}() // Output: Hello from anonymous function!
// Assign an anonymous function to a variable and invoke it
multiply := func(x, y int) int {
return x * y
}
result := multiply(3, 4)
fmt.Println("Product:", result) // Output: Product: 12
}