Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Common Function Patterns in Go with Practical Examples

2 min read .
Common Function Patterns in Go with Practical Examples

Functions are first-class values in Go: they can be assigned to variables, passed as arguments, returned from other functions, and wrapped in closures. Combined with multiple return values and defer, this gives Go a small but flexible set of function patterns.

1. Basic Functions

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

result := add(3, 4)
fmt.Println(result) // 7

Functions declare parameter types and, when needed, a return type after the parameter list.

2. Multiple Return Values

Go commonly returns a value together with an error:

func sqrt(x float64) (float64, error) {
    if x < 0 {
        return 0, fmt.Errorf("negative number")
    }
    return math.Sqrt(x), nil
}

result, err := sqrt(16)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(result) // 4
}

This pattern is central to idiomatic Go error handling.

3. Named Return Values

Return values can have names:

func swap(x, y int) (first, second int) {
    first = y
    second = x
    return
}

Named returns can be useful when they improve documentation, but explicit return expressions are often easier to read in longer functions.

4. Anonymous Functions

Functions do not need a declaration name:

result := func(a, b int) int {
    return a * b
}(3, 4)

fmt.Println(result) // 12

Anonymous functions are useful for callbacks, short helpers, and goroutines.

5. Closures and Returned Functions

A function can return another function that captures values from its surrounding scope:

func createMultiplier(factor int) func(int) int {
    return func(x int) int {
        return x * factor
    }
}

double := createMultiplier(2)
fmt.Println(double(5)) // 10

The returned closure keeps access to factor even after createMultiplier returns.

6. Deferred Function Calls

defer schedules a function call to run when the surrounding function returns:

func example() {
    defer fmt.Println("printed last")
    fmt.Println("printed first")
}

It is especially useful for cleanup such as closing files or unlocking mutexes after a resource has been acquired successfully.

7. Variadic Functions

A variadic parameter accepts zero or more values of the same type:

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

fmt.Println(sum(1, 2, 3))
fmt.Println(sum(4, 5, 6, 7, 8))

If you already have a slice, expand it with ...:

values := []int{1, 2, 3}
fmt.Println(sum(values...))

Conclusion

Go keeps function syntax deliberately compact, but the language still supports multiple results, errors, closures, anonymous functions, variadic parameters, and deferred calls. Understanding these patterns helps you write APIs that are both expressive and idiomatic.

Related Posts

Encrypt and Decrypt Data in Go with AES-GCM
Encrypt and Decrypt Data in Go with AES-GCM
Applications that store tokens, private configuration, or other sensitive values often need encryption at rest. Go includes everything required to implement modern symmetric encryption in its standard library. This example uses AES-GCM, an authenticated encryption mode that protects both confidentiality and integrity. That makes it a better default for new applications than older unauthenticated modes such as CFB. AES-GCM in Brief Symmetric encryption uses the same secret key for encryption and decryption. AES accepts 16-, 24-, or 32-byte keys for AES-128, AES-192, or AES-256. GCM adds authentication, so modified ciphertext is rejected during decryption. A fresh nonce must be used for every encryption operation with the same key. Complete Go Example Copy package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" ) func generateRandomKey() ([]byte, error) { key := make([]byte, 32) // AES-256 if _, err := rand.Read(key); err != nil { return nil, err } return key, nil } func encrypt(plaintext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err := rand.Read(nonce); err != nil { return nil, err } // Prefix the ciphertext with the nonce so decrypt can recover it. return gcm.Seal(nonce, nonce, plaintext, nil), nil } func decrypt(ciphertext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } nonceSize := gcm.NonceSize() if len(ciphertext) < nonceSize { return nil, fmt.Errorf("ciphertext too short") } nonce := ciphertext[:nonceSize] ciphertext = ciphertext[nonceSize:] return gcm.Open(nil, nonce, ciphertext, nil) } func main() { plaintext := []byte("Secret application data") key, err := generateRandomKey() if err != nil { panic(err) } ciphertext, err := encrypt(plaintext, key) if err != nil { panic(err) } fmt.Println("Ciphertext (base64):", base64.StdEncoding.EncodeToString(ciphertext)) decrypted, err := decrypt(ciphertext, key) if err != nil { panic(err) } fmt.Println("Decrypted text:", string(decrypted)) } How It Works generateRandomKey creates a cryptographically secure 32-byte key for AES-256. encrypt creates an AES cipher, wraps it with GCM, generates a random nonce, and encrypts the plaintext. The nonce is stored at the beginning of the returned byte slice. A nonce does not need to be secret, but it must not be reused with the same key. decrypt separates the nonce from the ciphertext and calls gcm.Open. If the ciphertext was modified, authentication fails and an error is returned. Key Management Matters The encryption code is only one part of a secure design. Do not hard-code real encryption keys in source control. In production, load keys from an appropriate secret-management system, protected environment, or key-management service.
Search Multiple Texts Concurrently with Goroutines in Go
Search Multiple Texts Concurrently with Goroutines in Go
Go makes concurrent work straightforward with goroutines. One practical example is searching for a word across many text values at the same time. Instead of checking each text sequentially, you can launch a goroutine for each item and wait for all searches to finish. Overview The program below will: Search for a word in a single text value with searchInText. Search multiple text values concurrently with searchWordInTexts. Print whether the word was found. Complete Example Copy package main import ( "fmt" "strings" "sync" ) // searchInText reports whether word occurs in text. func searchInText(text, word string) bool { if text == "" || word == "" { return false } // Make the search case-insensitive. text = strings.ToLower(text) word = strings.ToLower(word) return strings.Contains(text, word) } // searchWordInTexts searches multiple texts concurrently. func searchWordInTexts(texts []string, word string) bool { var wg sync.WaitGroup var mu sync.Mutex found := false for _, text := range texts { wg.Add(1) go func(t string) { defer wg.Done() if searchInText(t, word) { mu.Lock() found = true mu.Unlock() } }(text) } wg.Wait() return found } func main() { texts := []string{ "This is a long example text", "Another text for word searching", "This program uses goroutines for searching", } word := "program" if searchWordInTexts(texts, word) { fmt.Printf("Word '%s' was found in at least one text\n", word) } else { fmt.Printf("Word '%s' was not found\n", word) } } How It Works searchInText converts both the text and search term to lowercase, then uses strings.Contains for a case-insensitive match. searchWordInTexts uses sync.WaitGroup to wait for every goroutine and sync.Mutex to protect the shared found variable. main provides sample data, runs the concurrent search, and prints the result. A Practical Note For short in-memory strings, launching one goroutine per string may be slower than a simple loop because goroutines and synchronization have overhead. This pattern becomes more useful when each task is expensive or blocking, such as reading files, calling services, or processing large independent inputs.
chevron-up