View : 0

12/04/2026 18:16pm

EP.5 Functions in Go: Write Professional Code with Functions

EP.5 Functions in Go: Write Professional Code with Functions

#functions in Go

#return multiple values

#Go coding

#Go language

Functions in Go: Write Professional Code with Functions

Did you know? Functions help make your code shorter and easier to maintain. Today, we will explore just how easy it is to create functions in Go!

What is a Function?
A function is a set of instructions that we can call repeatedly, making your code cleaner, easier to read, and more maintainable.

Example of a Simple Function:

package main

import "fmt"

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

func main() {
    greet("Alice")
    greet("Bob")
}

 

Creating Functions in Go
In Go, a function consists of a function name, parameters (if any), and a return value (if any).

Example of a Function with a Return Value:

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

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

 

Multiple Parameters and Multiple Return Values
Go can return multiple values:

func swap(x, y int) (int, int) {
    return y, x
}

func main() {
    a, b := swap(1, 2)
    fmt.Println(a, b) // Output: 2 1
}

 

Functions without Parameters and Return Values
Some functions do not need to take any values and do not need to return anything, such as:

func sayHello() {
    fmt.Println("Hello, World!")
}