Fundamentals 8 min read

Master Go Functions: Scope, Defer, Panic & Recover Explained

This article delves into advanced Go function concepts, illustrating memory allocation diagrams, variable scopes, the use of const for globals, the behavior of defer statements, and handling errors with panic and recover, complete with code examples and visual outputs to deepen your understanding.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Go Functions: Scope, Defer, Panic & Recover Explained

Preface

Hey, I'm 星期八. In the previous article we covered basic Go functions; now we continue with advanced function topics.

Go Function Memory Allocation Diagram

Go's function memory allocation resembles heap allocation but is fundamentally different.

The stack holds the address of heap memory.

Verification

package main

import "fmt"

func say() string {
    return "ok"
}

func main() {
    fmt.Printf("say栈上的内容:%p
", say)
}

Essence

Function Scope

We revisit variable scope.

Global Variables

Global variables are defined outside all functions and persist for the program's lifetime; any function can access them. Conventionally, global variable names are uppercase.

Example with Global Variable

package main

import "fmt"

var NAME = "张三"

func say() string {
    fmt.Println(NAME)
    return "ok"
}

func main() {
    say()
    fmt.Println(NAME)
}

Modifying a global variable can cause unintended side effects.

Problem with Mutable Global Variable

package main

import "fmt"

var NAME = "张三"

func say() string {
    fmt.Println(NAME)
    NAME = "李四"
    return "ok"
}

func main() {
    say()
    fmt.Println(NAME)
}

To avoid this, use constants for immutable globals.

Using const to Solve the Problem

package main

import "fmt"

const NAME = "张三"

func say() string {
    fmt.Println(NAME)
    // NAME = "李四" // compile error: cannot assign to NAME
    return "ok"
}

func main() {
    say()
    fmt.Println(NAME)
}

Local Variables

Local variables are defined inside a function and are only accessible within that function.

package main

import (
    "fmt"
)

func say() string {
    var name = "张三"
    fmt.Println(name)
    return "ok"
}

func main() {
    say()
    // fmt.Println(name) // error: undefined: name
    for i := 0; i <= 1; i++ {
        var c = "66"
        fmt.Println(c) // 66
    }
    // fmt.Println(c) // error: undefined: c
}

defer

The defer statement schedules a function call to run just before the surrounding function returns, similar to a stack's LIFO behavior.

Single defer

package main

import "fmt"

func say() {
    // defer should be placed early
    defer fmt.Println("我是666")
    fmt.Println("你们都是最棒的")
}

func main() {
    say()
}

Multiple defer

package main

import "fmt"

func say() {
    defer fmt.Println(1)
    defer fmt.Println(2)
    defer fmt.Println(3)
    fmt.Println("你们都是最棒的")
}

func main() {
    say()
}

Defer calls execute in reverse order of their appearance.

Purpose of defer

Commonly used to release resources such as closing files or database connections when a function ends.

panic and recover

These mechanisms are analogous to Python's raise and try constructs; Go lacks a native try statement.

panic

package main

import "fmt"

func say() {
    var flag = true
    if flag {
        panic("OMG,撤了撤了,必须撤了")
    }
}

func main() {
    say()
    fmt.Println("继续呀...") // not executed
}

recover

package main

import "fmt"

func say() {
    defer func() {
        var err = recover()
        if err != nil {
            fmt.Println("尝试恢复...")
        }
    }()
    var flag = true
    if flag {
        panic("OMG,撤了撤了,必须撤了")
    }
}

func main() {
    say()
    fmt.Println("继续呀...")
}

When recover catches a panic, the program continues execution.

Summary

We have explored advanced Go function topics, including memory allocation, variable scopes, proper use of const for globals, defer behavior, and error handling with panic and recover. Feel free to leave comments if you have questions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GoconstfunctionsVariable Scopepanicdeferrecover
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.