Minggu, 25 Mei 2025

🧠 Go Function Reference Sheet

| Minggu, 25 Mei 2025
  1. Basic Function Syntax
func functionName(parameters) returnType {
    // function body
}

Example:

func greet(name string) string {
    return "Hello, " + name
}
  1. Calling a Function
message := greet("Alice")
fmt.Println(message) // Output: Hello, Alice
  1. Multiple Parameters
func add(a int, b int) int {
    return a + b
}

Shortcut: Same type for multiple parameters:

func add(a, b int) int {
    return a + b
}
  1. Multiple Return Values
func divide(dividend, divisor float64) (float64, string) {
    if divisor == 0 {
        return 0, "Error: Division by zero"
    }
    return dividend / divisor, "Success"
}
result, status := divide(10, 2)
  1. Named Return Values You can give names to return values — useful in longer functions.
func getFullName() (firstName, lastName string) {
    firstName = "John"
    lastName = "Doe"
    return // implicit return
}
  1. Variadic Functions (accept any number of arguments)
func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}
sum := sum(1, 2, 3, 4, 5) // Output: 15
  1. Anonymous Functions Functions without names, used for short tasks or inline.
func() {
    fmt.Println("I am anonymous")
}()

Or assign to a variable:

greet := func(name string) string {
    return "Hello, " + name
}
fmt.Println(greet("Bob"))
  1. Closures (Function with Access to Outer Variables)
func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

next := counter()
fmt.Println(next()) // 1
fmt.Println(next()) // 2
  1. Function as Parameter
func process(name string, f func(string) string) string {
    return f(name)
}

func shout(s string) string {
    return strings.ToUpper(s)
}

result := process("hello", shout)
  1. Scope in Go
  • Local scope: Variables declared inside a function are only accessible there.
  • Global scope: Variables declared outside of all functions are accessible everywhere in the same package.
  • Block scope: Variables inside {} are scoped to that block.
var globalVar = "I’m global"

func example() {
    localVar := "I’m local"
    fmt.Println(globalVar, localVar)
}
  1. Return Early (Best Practice) Avoid deep nesting using early returns:
func login(user string) string {
    if user == "" {
        return "No user provided"
    }
    return "Welcome " + user
}
  1. Recursive Function A function that calls itself:
func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

summary


Related Posts

Tidak ada komentar:

Posting Komentar