Go Functions:

Functions are essential building blocks in Go. They help you organize and reuse code. Go supports regular functions, return values, named returns, variadic functions, and even anonymous functions.

1. Basic Function

A simple function that prints a message:

go
package main
import "fmt"

func greet() {
  fmt.Println("Hello from Go!")
}

func main() {
  greet()
}

2. Function with Parameters

Functions can accept parameters to work with input data:

go
func greetUser(name string) {
  fmt.Println("Hello", name)
}

func main() {
  greetUser("Alice")
}

3. Function with Return Value

Functions can return results:

go
func add(a int, b int) int {
  return a + b
}

func main() {
  sum := add(3, 4)
  fmt.Println("Sum:", sum)
}

4. Multiple Return Values

You can return more than one value from a function:

go
func divide(a, b int) (int, int) {
  return a / b, a % b
}

func main() {
  q, r := divide(10, 3)
  fmt.Println("Quotient:", q, "Remainder:", r)
}

5. Named Return Values

You can name return values in the function signature:

go
func rectangleProps(length, width int) (area int, perimeter int) {
  area = length * width
  perimeter = 2 * (length + width)
  return
}

6. Variadic Functions

Functions can take a variable number of arguments:

go
func sum(numbers ...int) int {
  total := 0
  for _, num := range numbers {
    total += num
  }
  return total
}

func main() {
  fmt.Println(sum(1, 2, 3, 4))
}

7. Anonymous Functions

You can define functions without a name (useful for inline logic):

go
func main() {
  message := func(name string) string {
    return "Hi " + name
  }
  fmt.Println(message("Bob"))
}