GO Tutorial



FUNCTIONS IN GO


Functions in Go

Functions are reusable blocks of code that perform specific tasks. In Go, functions help organize your program into logical parts and promote code reusability.

Basic Function Syntax

func functionName(parameters) returnType {
    // function body
}
  

- func keyword declares a function.
- parameters are optional and specify inputs.
- returnType is optional and specifies the type of value the function returns.

Example: Function Without Parameters or Return Value

func greet() {
    fmt.Println("Hello, welcome to Go functions!")
}

func main() {
    greet()
}
  

Function With Parameters

func add(a int, b int) {
    fmt.Println("Sum:", a + b)
}

func main() {
    add(10, 20)
}
  

Function With Return Value

func multiply(x int, y int) int {
    return x * y
}

func main() {
    result := multiply(5, 7)
    fmt.Println("Product:", result)
}
  

Multiple Return Values

Go supports returning multiple values from a function, useful in many scenarios like returning results and errors together.

func swap(a, b string) (string, string) {
    return b, a
}

func main() {
    x, y := swap("hello", "world")
    fmt.Println(x, y)  // Output: world hello
}
  

Named Return Values

You can name the return values in the function signature and then simply use return without specifying variables.

func divide(a, b float64) (result float64, err error) {
    if b == 0 {
        err = fmt.Errorf("cannot divide by zero")
        return
    }
    result = a / b
    return
}

func main() {
    res, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", res)
    }
}
  

Summary

  • Functions are declared using the func keyword.
  • Parameters and return types can be specified; both can be omitted.
  • Functions can return multiple values, which is a powerful feature.
  • Named return values improve readability and can simplify return statements.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review