Functions Basics

Duration: 10 min  •  Difficulty: Medium

Functions are blocks of code wrapped so they can be called repeatedly. This helps with the DRY (Don't Repeat Yourself) principle.

Unique Feature in Go

One uniqueness of Go is that functions can return multiple values (Multiple Return Values). This is very useful, for example, for returning (result, error) simultaneously.

MAIN.GO
package main
import "fmt"
// Standard function: Input 2 ints, Output 1 int
func plus(a int, b int) int {
return a + b
}
// Multiple Return: Returning 2 strings at once
func getNames() (string, string) {
return "Raffi", "Rabbani"
}
func main() {
result := plus(10, 5)
fmt.Println("10 + 5 =", result)
// Capturing both return values
firstName, lastName := getNames()
fmt.Println("Fullname:", firstName, lastName)
}